diff --git a/src/Lumina.Application/Properties/AssemblyInfo.cs b/src/Lumina.Application/Properties/AssemblyInfo.cs index 543b6e1e..8dfab440 100644 --- a/src/Lumina.Application/Properties/AssemblyInfo.cs +++ b/src/Lumina.Application/Properties/AssemblyInfo.cs @@ -1,4 +1,4 @@ -using System.Reflection; +using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -16,4 +16,5 @@ using System.Runtime.InteropServices; // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("EACBCFD4-0FDD-4819-B2F2-056C812B2A3F")] -[assembly: InternalsVisibleTo("Lumina.Application.UnitTests")] \ No newline at end of file +[assembly: InternalsVisibleTo("Lumina.Application.UnitTests")] +[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] diff --git a/src/Lumina.Contracts/Enums/PhotoLibrary/ImageType.cs b/src/Lumina.Contracts/Enums/PhotoLibrary/ImageType.cs index 22d4c4e0..6ba8a7e9 100644 --- a/src/Lumina.Contracts/Enums/PhotoLibrary/ImageType.cs +++ b/src/Lumina.Contracts/Enums/PhotoLibrary/ImageType.cs @@ -1,24 +1,87 @@ -namespace Lumina.Contracts.Enums.PhotoLibrary; +namespace Lumina.Contracts.Enums.PhotoLibrary; /// /// Enumeration for known image types. /// public enum ImageType { + /// + /// No image type specified. + /// None, + + /// + /// Bitmap image format. + /// BMP, + + /// + /// Graphics Interchange Format (GIF). + /// GIF, + + /// + /// Portable Network Graphics (PNG) format. + /// PNG, + + /// + /// Tagged Image File Format (TIFF). + /// TIFF, + + /// + /// Joint Photographic Experts Group (JPEG) format. + /// JPEG, + + /// + /// Canon-specific JPEG format. + /// JPEG_CANON, + + /// + /// Unknown JPEG format. + /// JPEG_UNKNOWN, + + /// + /// Macintosh Picture (PICT) format. + /// PICT, + + /// + /// Icon (ICO) format. + /// ICO, + + /// + /// Photoshop Document (PSD) format. + /// PSD, + + /// + /// JPEG 2000 format. + /// JPEG2000, + + /// + /// AV1 Image File Format (AVIF). + /// AVIF, + + /// + /// Web Picture (WEBP) format. + /// WEBP, + + /// + /// Truevision TGA format. + /// TGA, - SVG, -} \ No newline at end of file + + /// + /// Scalable Vector Graphics (SVG) format. + /// + SVG +} diff --git a/src/Lumina.DataAccess/Properties/AssemblyInfo.cs b/src/Lumina.DataAccess/Properties/AssemblyInfo.cs index d1a3fa3c..d518cb91 100644 --- a/src/Lumina.DataAccess/Properties/AssemblyInfo.cs +++ b/src/Lumina.DataAccess/Properties/AssemblyInfo.cs @@ -1,4 +1,4 @@ -using System.Reflection; +using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -16,4 +16,5 @@ using System.Runtime.InteropServices; // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("F50EC9A6-696C-461E-B2F1-95B70BFE3DBF")] -[assembly: InternalsVisibleTo("Lumina.DataAccess.UnitTests")] \ No newline at end of file +[assembly: InternalsVisibleTo("Lumina.DataAccess.UnitTests")] +[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] diff --git a/src/Lumina.Domain/Common/DependencyInjection/DomainLayerServices.cs b/src/Lumina.Domain/Common/DependencyInjection/DomainLayerServices.cs index 326cf2cf..d662bad7 100644 --- a/src/Lumina.Domain/Common/DependencyInjection/DomainLayerServices.cs +++ b/src/Lumina.Domain/Common/DependencyInjection/DomainLayerServices.cs @@ -1,10 +1,12 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Environment; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Path; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; using Microsoft.Extensions.DependencyInjection; +using System; using System.IO.Abstractions; +using System.Runtime.InteropServices; #endregion namespace Lumina.Domain.Common.DependencyInjection; @@ -38,8 +40,9 @@ public static class DomainLayerServices services.AddScoped(); services.AddScoped(); services.AddScoped(); + services.AddScoped(); services.AddSingleton(); return services; } #endregion -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/DirectoryService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/DirectoryService.cs index 5582c26b..8866b082 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/DirectoryService.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/DirectoryService.cs @@ -143,9 +143,9 @@ public class DirectoryService : IDirectoryService ErrorOr newDirectoryPathResult = _environmentContext.DirectoryProviderService.CreateDirectory(path, name); if (newDirectoryPathResult.IsError) return newDirectoryPathResult.Errors; - ErrorOr dirNameResult = _environmentContext.DirectoryProviderService.GetFileName(path); - ErrorOr> dateModifiedResult = _environmentContext.DirectoryProviderService.GetLastWriteTime(path); - ErrorOr> dateCreatedResult = _environmentContext.DirectoryProviderService.GetCreationTime(path); + ErrorOr dirNameResult = _environmentContext.DirectoryProviderService.GetFileName(newDirectoryPathResult.Value); + ErrorOr> dateModifiedResult = _environmentContext.DirectoryProviderService.GetLastWriteTime(newDirectoryPathResult.Value); + ErrorOr> dateCreatedResult = _environmentContext.DirectoryProviderService.GetCreationTime(newDirectoryPathResult.Value); // if any error occurred, mark directory as Inaccessible if (dirNameResult.IsError || dateModifiedResult.IsError || dateCreatedResult.IsError) { diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileProviderService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileProviderService.cs index 8978437b..0e09a06c 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileProviderService.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileProviderService.cs @@ -159,18 +159,17 @@ internal class FileProviderService : IFileProviderService // check if the source file exists if (!_fileSystem.File.Exists(sourceFilePath.Path)) return Errors.FileManagement.FileNotFound; - string destinationFilePath; string fileName = _fileSystem.Path.GetFileName(sourceFilePath.Path); + string destinationFilePath = _fileSystem.Path.Combine(destinationDirectoryPath.Path, fileName); // when copying a file to the same location, just copy it with a new name if (_fileSystem.Path.GetDirectoryName(sourceFilePath.Path) == destinationDirectoryPath.Path) - destinationFilePath = CreateUniqueFilePath(destinationDirectoryPath.Path); + destinationFilePath = CreateUniqueFilePath(destinationFilePath); else { // check if there is already a file with the same name as the copied file, in the destination directory - if (_fileSystem.File.Exists(destinationDirectoryPath.Path + fileName)) + if (_fileSystem.File.Exists(destinationFilePath)) if (!overrideExisting) return Errors.FileManagement.FileAlreadyExists; - destinationFilePath = destinationDirectoryPath.Path + fileName; } try { @@ -218,7 +217,7 @@ internal class FileProviderService : IFileProviderService try { string fileName = _fileSystem.Path.GetFileName(sourceFilePath.Path); - string destinationFilePath = destinationDirectoryPath.Path + fileName; + string destinationFilePath = _fileSystem.Path.Combine(destinationDirectoryPath.Path, fileName); // if the destination file does not exist, perform a simple move if (!_fileSystem.File.Exists(destinationFilePath)) _fileSystem.File.Move(sourceFilePath.Path, destinationFilePath); diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileService.cs index 82b66d63..33be3f02 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileService.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileService.cs @@ -117,6 +117,8 @@ public class FileService : IFileService /// An containing either a copied file, or an error. public ErrorOr CopyFile(string sourceFilePath, string destinationDirectoryPath, bool? overrideExisting) { + if (string.IsNullOrWhiteSpace(destinationDirectoryPath)) + return Errors.FileManagement.InvalidPath; // make sure the paths are in the expected format if (!destinationDirectoryPath.EndsWith(_platformContext.PathStrategy.PathSeparator)) destinationDirectoryPath += _platformContext.PathStrategy.PathSeparator; @@ -181,6 +183,8 @@ public class FileService : IFileService /// An containing either a moved file, or an error. public ErrorOr MoveFile(string sourceFilePath, string destinationDirectoryPath, bool? overrideExisting) { + if (string.IsNullOrWhiteSpace(destinationDirectoryPath)) + return Errors.FileManagement.InvalidPath; // make sure the paths are in the expected format if (!destinationDirectoryPath.EndsWith(_platformContext.PathStrategy.PathSeparator)) destinationDirectoryPath += _platformContext.PathStrategy.PathSeparator; diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileSystemPermissionsService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileSystemPermissionsService.cs index 820b7943..96d64258 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileSystemPermissionsService.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileSystemPermissionsService.cs @@ -1,4 +1,4 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using Lumina.Contracts.Enums.FileSystem; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; @@ -16,7 +16,7 @@ namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.S /// /// Service for file system permissions. /// -internal class FileSystemPermissionsService : IFileSystemPermissionsService +internal class FileSystemPermissionsService : IFileSystemPermissionsService // TODO: refactor towards abstractions that could allow testing { #region ================================================================== FIELD MEMBERS ================================================================================ private readonly IPlatformContextManager _platformContextManager; @@ -210,4 +210,4 @@ internal class FileSystemPermissionsService : IFileSystemPermissionsService return allowAccess; } #endregion -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileTypeService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileTypeService.cs index 27142814..a05f8b57 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileTypeService.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/FileTypeService.cs @@ -23,7 +23,7 @@ public class FileTypeService : IFileTypeService #region ================================================================== FIELD MEMBERS ================================================================================ private readonly IFileSystem _fileSystem; private readonly IFileSystemPermissionsService _fileSystemPermissionsService; - private const int BUFFER_SIZE = 16; // 16 bytes should be more than enough for common images header types + private const int BUFFER_SIZE = 18; // 18 bytes should be more than enough for common images header types #endregion #region ====================================================================== CTOR ===================================================================================== @@ -119,7 +119,7 @@ public class FileTypeService : IFileTypeService if (buffer.Length < 18) return false; byte imageType = buffer[2]; - return imageType is 1 or 2 or 10; + return imageType is 1 or 2 or 3 or 9 or 10 or 11; } /// diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/PathService.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/PathService.cs index b3507eec..cb3cf783 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/PathService.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Services/PathService.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; +using Lumina.Domain.Common.Errors; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; using System.Collections.Generic; @@ -69,6 +70,8 @@ public class PathService : IPathService /// An containing the combined path, or an error. public ErrorOr CombinePath(string path, string name) { + if (string.IsNullOrWhiteSpace(path) || string.IsNullOrWhiteSpace(name)) + return Errors.FileManagement.InvalidPath; ErrorOr newPathResult = FileSystemPathId.Create(path); if (newPathResult.IsError) return newPathResult.Errors; diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/WindowsPathStrategy.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/WindowsPathStrategy.cs index bb375722..a0c60c23 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/WindowsPathStrategy.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Path/WindowsPathStrategy.cs @@ -4,7 +4,6 @@ using Lumina.Domain.Common.Errors; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; using System; using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; using System.IO.Abstractions; using System.Linq; using System.Text.RegularExpressions; @@ -50,7 +49,7 @@ public class WindowsPathStrategy : IWindowsPathStrategy return false; // regular expression to match valid absolute paths // this allows drive letters (e.g., C:\) and UNC paths (e.g., \\server\share) - string pathPattern = @"^[a-zA-Z]:\\(?:[a-zA-Z0-9\s()._-]+\\)*[a-zA-Z0-9\s()._-]*\\?$"; + string pathPattern = @"^(?:[a-zA-Z]:\\|\\\\[a-zA-Z0-9\s()._-]+\\[a-zA-Z0-9\s()._-]+)(?:[a-zA-Z0-9\s()._-]+\\)*[a-zA-Z0-9\s()._-]*\\?$"; return Regex.IsMatch(path.Path, pathPattern); } @@ -89,8 +88,8 @@ public class WindowsPathStrategy : IWindowsPathStrategy /// An containing the path segments, or an error. public ErrorOr> ParsePath(FileSystemPathId path) { - // Windows paths usually start with a drive letter and colon, e.g., "C:" - if (!path.Path.Contains(':') || !path.Path.Contains(PathSeparator) || !char.IsLetter(path.Path[0]) || path.Path[1] != ':' || path.Path[2] != PathSeparator) + // Windows paths usually start with a drive letter and colon, e.g., "C:", or "\\" (UNC paths) + if (!(path.Path.StartsWith(@"\\") || (path.Path.Length >= 3 && char.IsLetter(path.Path[0]) && path.Path[1] == ':' && path.Path[2] == PathSeparator))) return Errors.FileManagement.InvalidPath; IEnumerable> getPathSegmentsResults = GetPathSegments(); foreach (ErrorOr getPathSegmentsResult in getPathSegmentsResults) @@ -99,20 +98,39 @@ public class WindowsPathStrategy : IWindowsPathStrategy return ErrorOrFactory.From(getPathSegmentsResults.Select(getPathSegmentsResult => getPathSegmentsResult.Value)); IEnumerable> GetPathSegments() { - // the drive segment - yield return PathSegment.Create(path.Path[..2], isDirectory: false, isDrive: true); - // extract the other segments - string[] segments = path.Path[3..].Split(new[] { PathSeparator }, StringSplitOptions.RemoveEmptyEntries); - for (int i = 0; i < segments.Length; i++) + if (path.Path.StartsWith(@"\\")) { - string segment = segments[i]; - bool isDirectory; - if (segment.Contains('.')) - isDirectory = i != segments.Length - 1 || path.Path.EndsWith(PathSeparator); // check if it's the last segment or if the next segment also contains a path delimiter - else - isDirectory = true; - yield return PathSegment.Create(segment, isDirectory, isDrive: false); + // handle UNC path + yield return PathSegment.Create(@"\\", isDirectory: false, isDrive: true); + + string[] segments = path.Path[2..].Split(new[] { PathSeparator }, StringSplitOptions.RemoveEmptyEntries); + for (int i = 0; i < segments.Length; i++) + yield return CreatePathSegment(segments[i], i, segments.Length); } + else // handle regular Windows path + { + // the drive segment + yield return PathSegment.Create(path.Path[..2], isDirectory: false, isDrive: true); + // extract the other segments + string[] segments = path.Path[3..].Split(new[] { PathSeparator }, StringSplitOptions.RemoveEmptyEntries); + for (int i = 0; i < segments.Length; i++) + { + string segment = segments[i]; + bool isDirectory; + if (segment.Contains('.')) + isDirectory = i != segments.Length - 1 || path.Path.EndsWith(PathSeparator); // check if it's the last segment or if the next segment also contains a path delimiter + else + isDirectory = true; + yield return PathSegment.Create(segment, isDirectory, isDrive: false); + } + } + } + ErrorOr CreatePathSegment(string segment, int index, int totalSegments) + { + bool isDirectory = segment.Contains('.') + ? index != totalSegments - 1 || path.Path.EndsWith(PathSeparator) + : true; + return PathSegment.Create(segment, isDirectory, isDrive: false); } } @@ -126,22 +144,30 @@ public class WindowsPathStrategy : IWindowsPathStrategy // validation: ensure the path is not null or empty if (!IsValidPath(path)) return Errors.FileManagement.InvalidPath; - // if path is just a drive letter followed by ":\", return null - if (Regex.IsMatch(path.Path, @"^[a-zA-Z]:\\?$")) + // trim trailing backslash for consistent processing + string tempPath = path.Path.TrimEnd(PathSeparator); + // check for UNC path + if (tempPath.StartsWith(@"\\")) + { + string[] parts = tempPath.Split(PathSeparator, StringSplitOptions.RemoveEmptyEntries); + if (parts.Length <= 2) + return Errors.FileManagement.CannotNavigateUp; + // if it's a single-level UNC path, return the UNC root + if (parts.Length == 3) + return ParsePath(FileSystemPathId.Create($@"\\{parts[0]}\{parts[1]}").Value); + } // check for drive root (both with and without trailing backslash) + else if ((tempPath.Length == 2 && tempPath[1] == ':') || (tempPath.Length == 3 && tempPath[1] == ':' && tempPath[2] == PathSeparator)) return Errors.FileManagement.CannotNavigateUp; - // trim trailing slash for consistent processing - string tempPath = path.Path; - if (tempPath.EndsWith('\\')) - tempPath = tempPath.TrimEnd(PathSeparator); - // find the last occurrence of a slash + // find the last occurrence of a backslash int lastIndex = tempPath.LastIndexOf(PathSeparator); - // if there's no slash found (shouldn't happen due to previous steps), or if we are at the root level after trimming, return error - if (lastIndex < 0) - return Errors.FileManagement.CannotNavigateUp; - // if we are at the drive root level after trimming, return drive root, otherwise, return the path up to the last slash - ErrorOr newPathResult = FileSystemPathId.Create(lastIndex == 2 && tempPath[1] == ':' ? tempPath[..3] : tempPath[..lastIndex]); + // if there's no backslash found or it's at the root level, return the root + if (lastIndex <= 2) + return ParsePath(FileSystemPathId.Create(tempPath[..3]).Value); + // return the path up to the last backslash + ErrorOr newPathResult = FileSystemPathId.Create(tempPath[..lastIndex]); if (newPathResult.IsError) return newPathResult.Errors; + return ParsePath(newPathResult.Value); } @@ -163,28 +189,30 @@ public class WindowsPathStrategy : IWindowsPathStrategy { if (!IsValidPath(path)) return Errors.FileManagement.InvalidPath; - // check if the path starts with a drive letter (e.g., "C:") - if (path.Path.Length >= 2 && char.IsLetter(path.Path[0]) && path.Path[1] == ':') + // handle UNC paths (e.g., \\server\share\folder) + if (path.Path.StartsWith(@"\\")) { - string root = path.Path[..2]; - if (path.Path.Length > 2 && path.Path[2] == PathSeparator) - root += PathSeparator; - return PathSegment.Create(root, isDirectory: true, isDrive: true); + // find the position of the second backslash (after \\server) + int secondBackslash = path.Path.IndexOf('\\', 2); + if (secondBackslash == -1) + return Errors.FileManagement.InvalidPath; // invalid UNC path, missing server name + // find the position of the third backslash (after \\server\share) + int thirdBackslash = path.Path.IndexOf('\\', secondBackslash + 1); + if (thirdBackslash == -1) + thirdBackslash = path.Path.Length; // no third backslash, use entire path + // return the UNC root (\\server\share\) + return PathSegment.Create(path.Path[..thirdBackslash] + "\\", isDirectory: true, isDrive: false); } - // check for UNC paths (e.g., "\\server\share") - if (path.Path.StartsWith('\\')) - { - ErrorOr> parseResult = ParsePath(path); - if (parseResult.IsError) - return parseResult.Errors; - - List segments = parseResult.Value.ToList(); - if (segments.Count >= 2) - { - string root = $@"\\{segments[0].Name}\{segments[1].Name}\"; - return PathSegment.Create(root, isDirectory: true, isDrive: false); - } + else // handle drive letter paths (e.g., C:\folder) + { + // check if the path starts with a drive letter followed by a colon (e.g., C:) + // path.Path.Length >= 2: Ensure the path is at least 2 characters long + // char.IsLetter(path.Path[0]): First character should be a letter + // path.Path[1] == ':': Second character should be a colon + if (path.Path.Length >= 2 && char.IsLetter(path.Path[0]) && path.Path[1] == ':') + return PathSegment.Create(path.Path[..2] + "\\", isDirectory: true, isDrive: true); // return the drive root (e.g., C:\) } + // if we reach here, the path is neither a valid UNC path nor a valid drive path return Errors.FileManagement.InvalidPath; } #endregion diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/IOperatingSystemInfo.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/IOperatingSystemInfo.cs new file mode 100644 index 00000000..4a6875c4 --- /dev/null +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/IOperatingSystemInfo.cs @@ -0,0 +1,20 @@ +#region ========================================================================= USING ===================================================================================== +using System.Runtime.InteropServices; +#endregion + +namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; + +/// +/// Interface for checking the type of the current Operating System platform. +/// +public interface IOperatingSystemInfo +{ + #region ===================================================================== METHODS =================================================================================== + /// + /// Determines if the current Operating System plaform is . + /// + /// The Operating System platform to check against. + /// if tthe current Operating System platform is equal to , otherwise. + bool IsOSPlatform(OSPlatform platform); + #endregion +} diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/OperatingSystemInfo.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/OperatingSystemInfo.cs new file mode 100644 index 00000000..f2404710 --- /dev/null +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/OperatingSystemInfo.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics.CodeAnalysis; +using System.Runtime.InteropServices; +#endregion + +namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; + +/// +/// Class for checking the type of the current Operating System platform. +/// +[ExcludeFromCodeCoverage] +internal class OperatingSystemInfo : IOperatingSystemInfo +{ + #region ===================================================================== METHODS =================================================================================== + /// + /// Determines if the current Operating System plaform is . + /// + /// The Operating System platform to check against. + /// if tthe current Operating System platform is equal to , otherwise. + public bool IsOSPlatform(OSPlatform platform) + { + return RuntimeInformation.IsOSPlatform(platform); + } + #endregion +} diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/PlatformContextManager.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/PlatformContextManager.cs index d3eb8446..946351df 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/PlatformContextManager.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/PlatformContextManager.cs @@ -1,4 +1,4 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using Lumina.Contracts.Enums.FileSystem; using System; using System.Runtime.InteropServices; @@ -14,6 +14,7 @@ public class PlatformContextManager : IPlatformContextManager #region ================================================================== FIELD MEMBERS ================================================================================ private IPlatformContext? _currentPlatformContext; private readonly IPlatformContextFactory _platformContextFactory; + private readonly IOperatingSystemInfo _operatingSystemInfo; #endregion #region ====================================================================== CTOR ===================================================================================== @@ -21,9 +22,11 @@ public class PlatformContextManager : IPlatformContextManager /// Initializes a new instance of the class. /// /// Injected factory for creating platform contexts. - public PlatformContextManager(IPlatformContextFactory platformContextFactory) + /// Injected class for checking the platform type of the current Operating System. + public PlatformContextManager(IPlatformContextFactory platformContextFactory, IOperatingSystemInfo operatingSystemInfo) { _platformContextFactory = platformContextFactory; + _operatingSystemInfo = operatingSystemInfo; } #endregion @@ -37,7 +40,7 @@ public class PlatformContextManager : IPlatformContextManager // set a default context if none is set if (_currentPlatformContext is null) { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + if (_operatingSystemInfo.IsOSPlatform(OSPlatform.Linux)) SetCurrentPlatform(PlatformType.Unix); else SetCurrentPlatform(PlatformType.Windows); @@ -61,4 +64,4 @@ public class PlatformContextManager : IPlatformContextManager }; } #endregion -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/UnixPlatformContext.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/UnixPlatformContext.cs index 75e5e7b2..fedf3d70 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/UnixPlatformContext.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/UnixPlatformContext.cs @@ -1,4 +1,4 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using Lumina.Contracts.Enums.FileSystem; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Path; #endregion @@ -19,7 +19,7 @@ internal class UnixPlatformContext : IUnixPlatformContext /// /// Gets the path strategy for Unix platforms. /// - public IPathStrategy PathStrategy { get; private set; } + public IPathStrategy PathStrategy { get; } #endregion #region ====================================================================== CTOR ===================================================================================== @@ -32,4 +32,4 @@ internal class UnixPlatformContext : IUnixPlatformContext PathStrategy = unixPathStrategy; } #endregion -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/WindowsPlatformContext.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/WindowsPlatformContext.cs index 38ccb4cd..93f7f2a4 100644 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/WindowsPlatformContext.cs +++ b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/Strategies/Platform/WindowsPlatformContext.cs @@ -1,4 +1,4 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using Lumina.Contracts.Enums.FileSystem; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Path; #endregion @@ -19,7 +19,7 @@ public class WindowsPlatformContext : IWindowsPlatformContext /// /// Gets the path strategy for Windows platforms. /// - public IPathStrategy PathStrategy { get; private set; } + public IPathStrategy PathStrategy { get; } #endregion #region ====================================================================== CTOR ===================================================================================== @@ -32,4 +32,4 @@ public class WindowsPlatformContext : IWindowsPlatformContext PathStrategy = windowsPathStrategy; } #endregion -} \ No newline at end of file +} diff --git a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/FileSystemId.cs b/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/FileSystemId.cs deleted file mode 100644 index 40cce931..00000000 --- a/src/Lumina.Domain/Core/Aggregates/FileManagement/FileManagementAggregate/ValueObjects/FileSystemId.cs +++ /dev/null @@ -1,52 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Models.Core; -using System; -using System.Collections.Generic; -using System.Diagnostics; -#endregion - -namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; - -/// -/// Value Object for the Id of a book. -/// -[DebuggerDisplay("{Value}")] -public sealed class FileSystemId : EntityId -{ - #region ====================================================================== CTOR ===================================================================================== - /// - /// Initializes a new instance of the class. - /// - /// The value representing this object. - private FileSystemId(Guid value) : base(value) - { - } - #endregion - - #region ===================================================================== METHODS =================================================================================== - /// - /// Creates a new instance of the class. - /// - /// The created instance. - public static FileSystemId CreateUnique() - { - return new FileSystemId(Guid.NewGuid()); - } - - /// - /// Creates a new instance of the class, from a pre-existing . - /// - /// The value used to create the instance. - /// The created instance. - public static FileSystemId Create(Guid value) - { - return new FileSystemId(value); - } - - /// - public override IEnumerable GetEqualityComponents() - { - yield return Value; - } - #endregion -} \ No newline at end of file diff --git a/src/Lumina.Domain/Properties/AssemblyInfo.cs b/src/Lumina.Domain/Properties/AssemblyInfo.cs index 6c3af4fa..0727ec2f 100644 --- a/src/Lumina.Domain/Properties/AssemblyInfo.cs +++ b/src/Lumina.Domain/Properties/AssemblyInfo.cs @@ -1,4 +1,4 @@ -using System.Reflection; +using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -16,4 +16,5 @@ using System.Runtime.InteropServices; // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("E4C6366D-8187-459B-BB7F-1BE077DCFB25")] -[assembly: InternalsVisibleTo("Lumina.Domain.UnitTests")] \ No newline at end of file +[assembly: InternalsVisibleTo("Lumina.Domain.UnitTests")] +[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] diff --git a/src/Lumina.Infrastructure/Properties/AssemblyInfo.cs b/src/Lumina.Infrastructure/Properties/AssemblyInfo.cs index d4fe95e5..09c567c1 100644 --- a/src/Lumina.Infrastructure/Properties/AssemblyInfo.cs +++ b/src/Lumina.Infrastructure/Properties/AssemblyInfo.cs @@ -1,4 +1,4 @@ -using System.Reflection; +using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -16,4 +16,5 @@ using System.Runtime.InteropServices; // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("EADA449A-48B9-4A97-97E8-73D23E9EC56A")] -[assembly: InternalsVisibleTo("Lumina.Infrastructure.UnitTests")] \ No newline at end of file +[assembly: InternalsVisibleTo("Lumina.Infrastructure.UnitTests")] +[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] diff --git a/src/Lumina.Presentation.Api/Properties/AssemblyInfo.cs b/src/Lumina.Presentation.Api/Properties/AssemblyInfo.cs index c448066f..7ec7c41a 100644 --- a/src/Lumina.Presentation.Api/Properties/AssemblyInfo.cs +++ b/src/Lumina.Presentation.Api/Properties/AssemblyInfo.cs @@ -1,4 +1,4 @@ -using System.Reflection; +using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -16,4 +16,5 @@ using System.Runtime.InteropServices; // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("D910C582-3905-4DD3-8BCA-0CB30852704E")] -[assembly: InternalsVisibleTo("Lumina.Presentation.Api.UnitTests")] \ No newline at end of file +[assembly: InternalsVisibleTo("Lumina.Presentation.Api.UnitTests")] +[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] diff --git a/src/Lumina.Presentation.Web/Properties/AssemblyInfo.cs b/src/Lumina.Presentation.Web/Properties/AssemblyInfo.cs index ceea1d9f..d1584f9a 100644 --- a/src/Lumina.Presentation.Web/Properties/AssemblyInfo.cs +++ b/src/Lumina.Presentation.Web/Properties/AssemblyInfo.cs @@ -17,3 +17,4 @@ using System.Runtime.InteropServices; [assembly: Guid("4E3EEA67-7C92-4588-9183-03140627D564")] [assembly: InternalsVisibleTo("Lumina.Presentation.Web.UnitTests")] +[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Fixtures/DirectoryFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Fixtures/DirectoryFixture.cs index 6882de15..20e1f772 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Fixtures/DirectoryFixture.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Fixtures/DirectoryFixture.cs @@ -37,7 +37,14 @@ public class DirectoryFixture /// /// Creates a random valid . /// - /// The created . + /// Optional. The directory path. If not provided, a random path is generated. + /// Optional. The directory name. If not provided, a random name is generated. + /// Optional. The directory's creation date. If not provided, a random past date is generated. + /// Optional. The directory's modification date. If not provided, a recent date is generated. + /// Optional. The directory's status. If not provided, a random status is assigned. + /// Optional. A list of child items to be added to the directory. + /// A newly created Directory instance. + /// Thrown if the Directory creation fails. public Directory CreateDirectory( string? path = null, string? name = null, diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandlerTests.cs index 647000b3..3f4f400a 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandlerTests.cs @@ -3,22 +3,12 @@ using AutoFixture; using AutoFixture.AutoNSubstitute; using ErrorOr; using FluentAssertions; -using Lumina.Application.Common.DataAccess.Repositories.Books; -using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Core.FileManagement.Directories.Queries.GetDirectories; -using Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook; -using Lumina.Application.UnitTests.Common.Setup; using Lumina.Application.UnitTests.Core.FileManagement.Directories.Fixtures; using Lumina.Application.UnitTests.Core.FileManagement.Directories.Queries.GetDirectories.Fixtures; -using Lumina.Application.UnitTests.Core.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook.Fixtures; -using Lumina.Contracts.Enums.BookLibrary; -using Lumina.Contracts.Models.Common; -using Lumina.Contracts.Models.WrittenContentLibrary.BookLibrary; using Lumina.Contracts.Responses.FileManagement; -using Lumina.Domain.Common.Errors; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; -using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate; using MapsterMapper; using NSubstitute; using System; diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Common/Primitives/OptionalTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Common/Primitives/OptionalTests.cs new file mode 100644 index 00000000..5309bbe0 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Common/Primitives/OptionalTests.cs @@ -0,0 +1,137 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Domain.Common.Primitives; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Common.Primitives; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class OptionalTests +{ + #region ===================================================================== METHODS =================================================================================== + [Fact] + public void Some_WhenCreatingOptionalWithValue_ShouldHaveValueAndCorrectValue() + { + // Arrange + int value = 42; + + // Act + Optional optional = Optional.Some(value); + + // Assert + optional.HasValue.Should().BeTrue(); + optional.Value.Should().Be(value); + } + + [Fact] + public void None_WhenCreatingOptionalWithoutValue_ShouldNotHaveValueAndHaveDefaultValue() + { + // Arrange & Act + Optional optional = Optional.None(); + + // Assert + optional.HasValue.Should().BeFalse(); + optional.Value.Should().Be(default); + } + + [Fact] + public void ImplicitConversion_WhenConvertingValueToOptional_ShouldCreateOptionalWithValue() + { + // Arrange + string value = "test"; + + // Act + Optional optional = value; + + // Assert + optional.HasValue.Should().BeTrue(); + optional.Value.Should().Be(value); + } + + [Fact] + public void FromNullable_WhenCreatingFromNonNullReferenceType_ShouldCreateOptionalWithValue() + { + // Arrange + string? nullableValue = "test"; + + // Act + Optional optional = Optional.FromNullable(nullableValue); + + // Assert + optional.HasValue.Should().BeTrue(); + optional.Value.Should().Be(nullableValue); + } + + [Fact] + public void FromNullable_WhenCreatingFromNullReferenceType_ShouldCreateOptionalWithoutValue() + { + // Arrange + string? nullableValue = null; + + // Act + Optional optional = Optional.FromNullable(nullableValue); + + // Assert + optional.HasValue.Should().BeFalse(); + optional.Value.Should().BeNull(); + } + + [Fact] + public void FromNullable_WhenCreatingFromNonNullValueType_ShouldCreateOptionalWithValue() + { + // Arrange + int? nullableValue = 42; + + // Act + Optional optional = Optional.FromNullable(nullableValue); + + // Assert + optional.HasValue.Should().BeTrue(); + optional.Value.Should().Be(nullableValue.Value); + } + + [Fact] + public void FromNullable_WhenCreatingFromNullValueType_ShouldCreateOptionalWithoutValue() + { + // Arrange + int? nullableValue = null; + + // Act + Optional optional = Optional.FromNullable(nullableValue); + + // Assert + optional.HasValue.Should().BeFalse(); + optional.Value.Should().Be(default); + } + + [Fact] + public void ToString_WhenOptionalHasValue_ShouldReturnValueToString() + { + // Arrange + Optional optional = Optional.Some(42); + + // Act + string result = optional.ToString(); + + // Assert + result.Should().Be("42"); + } + + [Fact] + public void ToString_WhenOptionalHasNoValue_ShouldReturnEmptyString() + { + // Arrange + Optional optional = Optional.None(); + + // Act + string result = optional.ToString(); + + // Assert + result.Should().BeEmpty(); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Entities/DirectoryTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Entities/DirectoryTests.cs new file mode 100644 index 00000000..ba523c32 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Entities/DirectoryTests.cs @@ -0,0 +1,138 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FluentAssertions; +using Lumina.Contracts.Enums.FileSystem; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; +using System; +using System.Diagnostics.CodeAnalysis; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate; +using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Fixtures; +#endregion + +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Entities; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DirectoryTests +{ + #region ===================================================================== METHODS =================================================================================== + [Fact] + public void Create_WhenCalledWithValidParameters_ShouldReturnSuccessfulResult() + { + // Arrange + string path = "/valid/path"; + string name = "TestDirectory"; + Optional dateCreated = DateTime.Now; + Optional dateModified = DateTime.Now; + + // Act + ErrorOr result = Directory.Create(path, name, dateCreated, dateModified); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Name.Should().Be(name); + result.Value.DateCreated.Should().Be(dateCreated); + result.Value.DateModified.Should().Be(dateModified); + result.Value.Status.Should().Be(FileSystemItemStatus.Accessible); + } + + [Fact] + public void Create_WhenCalledWithInvalidPath_ShouldReturnError() + { + // Arrange + string invalidPath = ""; + string name = "TestDirectory"; + Optional dateCreated = DateTime.Now; + Optional dateModified = DateTime.Now; + + // Act + ErrorOr result = Directory.Create(invalidPath, name, dateCreated, dateModified); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + } + + [Fact] + public void Create_WhenCalledWithFileSystemPathId_ShouldReturnSuccessfulResult() + { + // Arrange + ErrorOr pathIdResult = FileSystemPathId.Create("/valid/path"); + pathIdResult.IsError.Should().BeFalse(); + FileSystemPathId pathId = pathIdResult.Value; + string name = "TestDirectory"; + Optional dateCreated = DateTime.Now; + Optional dateModified = DateTime.Now; + + // Act + ErrorOr result = Directory.Create(pathId, name, dateCreated, dateModified); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Id.Should().Be(pathId); + result.Value.Name.Should().Be(name); + result.Value.DateCreated.Should().Be(dateCreated); + result.Value.DateModified.Should().Be(dateModified); + result.Value.Status.Should().Be(FileSystemItemStatus.Accessible); + } + + [Fact] + public void UpdateLastModified_WhenCalled_ShouldUpdateDateModified() + { + // Arrange + ErrorOr directoryResult = Directory.Create("/valid/path", "TestDirectory", Optional.None(), Optional.None()); + directoryResult.IsError.Should().BeFalse(); + Directory directory = directoryResult.Value; + DateTime newDate = DateTime.Now; + + // Act + ErrorOr result = directory.UpdateLastModified(newDate); + + // Assert + result.IsError.Should().BeFalse(); + directory.DateModified.Value.Should().Be(newDate); + } + + [Fact] + public void AddItem_WhenCalled_ShouldAddItemToCollection() + { + // Arrange + ErrorOr directoryResult = Directory.Create("/valid/path", "TestDirectory", Optional.None(), Optional.None()); + directoryResult.IsError.Should().BeFalse(); + Directory directory = directoryResult.Value; + FileSystemItem item = new FileSystemItemFixture(FileSystemPathId.Create("/mock/path").Value, "MockItem", FileSystemItemType.File); + + // Act + ErrorOr result = directory.AddItem(item); + + // Assert + result.IsError.Should().BeFalse(); + directory.Items.Should().Contain(item); + } + + [Fact] + public void RemoveItem_WhenCalledWithExistingItem_ShouldRemoveItemFromCollection() + { + // Arrange + ErrorOr directoryResult = Directory.Create("/valid/path", "TestDirectory", Optional.None(), Optional.None()); + directoryResult.IsError.Should().BeFalse(); + Directory directory = directoryResult.Value; + FileSystemItem item = new FileSystemItemFixture(FileSystemPathId.Create("/mock/path").Value, "MockItem", FileSystemItemType.File); + directory.AddItem(item); + + // Act + ErrorOr result = directory.RemoveItem(item); + + // Assert + result.IsError.Should().BeFalse(); + directory.Items.Should().NotContain(item); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Entities/FileTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Entities/FileTests.cs new file mode 100644 index 00000000..718ff751 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Entities/FileTests.cs @@ -0,0 +1,158 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FluentAssertions; +using Lumina.Contracts.Enums.FileSystem; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Entities; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class FileTests +{ + #region ===================================================================== METHODS =================================================================================== + [Fact] + public void Create_WhenCalledWithValidParameters_ShouldReturnSuccessfulResult() + { + // Arrange + string path = "/valid/path/file.txt"; + string name = "file.txt"; + Optional dateCreated = DateTime.Now; + Optional dateModified = DateTime.Now; + long size = 1024; + + // Act + ErrorOr result = File.Create(path, name, dateCreated, dateModified, size); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Name.Should().Be(name); + result.Value.DateCreated.Should().Be(dateCreated); + result.Value.DateModified.Should().Be(dateModified); + result.Value.Size.Should().Be(size); + result.Value.Status.Should().Be(FileSystemItemStatus.Accessible); + } + + [Fact] + public void Create_WhenCalledWithInvalidPath_ShouldReturnError() + { + // Arrange + string invalidPath = ""; + string name = "file.txt"; + Optional dateCreated = DateTime.Now; + Optional dateModified = DateTime.Now; + long size = 1024; + + // Act + ErrorOr result = File.Create(invalidPath, name, dateCreated, dateModified, size); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + } + + [Fact] + public void Create_WhenCalledWithFileSystemPathId_ShouldReturnSuccessfulResult() + { + // Arrange + ErrorOr pathIdResult = FileSystemPathId.Create("/valid/path/file.txt"); + pathIdResult.IsError.Should().BeFalse(); + FileSystemPathId pathId = pathIdResult.Value; + string name = "file.txt"; + Optional dateCreated = DateTime.Now; + Optional dateModified = DateTime.Now; + long size = 1024; + + // Act + ErrorOr result = File.Create(pathId, name, dateCreated, dateModified, size); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Id.Should().Be(pathId); + result.Value.Name.Should().Be(name); + result.Value.DateCreated.Should().Be(dateCreated); + result.Value.DateModified.Should().Be(dateModified); + result.Value.Size.Should().Be(size); + result.Value.Status.Should().Be(FileSystemItemStatus.Accessible); + } + + [Fact] + public void UpdateLastModified_WhenCalled_ShouldUpdateDateModified() + { + // Arrange + ErrorOr fileResult = File.Create("/valid/path/file.txt", "file.txt", Optional.None(), Optional.None(), 1024); + fileResult.IsError.Should().BeFalse(); + File file = fileResult.Value; + DateTime newDate = DateTime.Now; + + // Act + ErrorOr result = file.UpdateLastModified(newDate); + + // Assert + result.IsError.Should().BeFalse(); + file.DateModified.Value.Should().Be(newDate); + } + + [Fact] + public void UpdateSize_WhenCalled_ShouldUpdateFileSize() + { + // Arrange + ErrorOr fileResult = File.Create("/valid/path/file.txt", "file.txt", Optional.None(), Optional.None(), 1024); + fileResult.IsError.Should().BeFalse(); + File file = fileResult.Value; + long newSize = 2048; + + // Act + ErrorOr result = file.UpdateSize(newSize); + + // Assert + result.IsError.Should().BeFalse(); + file.Size.Should().Be(newSize); + } + + [Fact] + public void Rename_WhenCalledWithValidName_ShouldUpdateFileName() + { + // Arrange + ErrorOr fileResult = File.Create("/valid/path/file.txt", "file.txt", Optional.None(), Optional.None(), 1024); + fileResult.IsError.Should().BeFalse(); + File file = fileResult.Value; + string newName = "newfile.txt"; + + // Act + ErrorOr result = file.Rename(newName); + + // Assert + result.IsError.Should().BeFalse(); + file.Name.Should().Be(newName); + } + + [Fact] + public void Rename_WhenCalledWithEmptyName_ShouldReturnError() + { + // Arrange + ErrorOr fileResult = File.Create("/valid/path/file.txt", "file.txt", Optional.None(), Optional.None(), 1024); + fileResult.IsError.Should().BeFalse(); + File file = fileResult.Value; + string emptyName = ""; + + // Act + ErrorOr result = file.Rename(emptyName); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.NameCannotBeEmpty); + file.Name.Should().Be("file.txt"); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Entities/Fixtures/DirectoryFixture.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Entities/Fixtures/DirectoryFixture.cs new file mode 100644 index 00000000..ca7b480e --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Entities/Fixtures/DirectoryFixture.cs @@ -0,0 +1,116 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using ErrorOr; +using Lumina.Contracts.Enums.FileSystem; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Entities.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class DirectoryFixture +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly Faker _faker; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public DirectoryFixture() + { + _faker = new Faker(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + /// + /// Creates a random valid . + /// + /// Optional. The directory path. If not provided, a random path is generated. + /// Optional. The directory name. If not provided, a random name is generated. + /// Optional. The directory's creation date. If not provided, a random past date is generated. + /// Optional. The directory's modification date. If not provided, a recent date is generated. + /// Optional. The directory's status. If not provided, a random status is assigned. + /// Optional. A list of child items to be added to the directory. + /// A newly created instance. + /// Thrown if the creation fails. + public Directory CreateDirectory( + string? path = null, + string? name = null, + Optional? dateCreated = null, + Optional? dateModified = null, + FileSystemItemStatus? status = null, + List? childItems = null) + { + path ??= _faker.System.FilePath(); + name ??= _faker.System.FileName(); + dateCreated ??= Optional.Some(_faker.Date.Past()); + dateModified ??= Optional.Some(_faker.Date.Recent()); + status ??= _faker.PickRandom(); + + ErrorOr directoryResult = Directory.Create(path, name, dateCreated.Value, dateModified.Value, status.Value); + + if (directoryResult.IsError) + throw new InvalidOperationException("Failed to create Directory: " + string.Join(", ", directoryResult.Errors)); + Directory directory = directoryResult.Value; + + if (childItems != null) + foreach (FileSystemItem item in childItems) + directory.AddItem(item); + return directory; + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return Enumerable.Range(0, count).Select(_ => CreateDirectory()).ToList(); + } + + /// + /// Creates a list of nested objects with a hierarchical structure. + /// + /// The number of top-level directories to create. Default is 3. + /// The maximum depth of the directory hierarchy. Default is 3. + /// The maximum number of child items (files or directories) per directory. Default is 3. + /// A list of objects with nested structures. + public List CreateManyNested(int count = 3, int maxDepth = 3, int maxChildrenPerDirectory = 3) + { + return Enumerable.Range(0, count).Select(_ => CreateNestedDirectory(1, maxDepth, maxChildrenPerDirectory)).ToList(); + } + + /// + /// Recursively creates a nested structure. + /// + /// The current depth in the directory hierarchy. + /// The maximum allowed depth for the directory hierarchy. + /// The maximum number of child items (files or directories) allowed per directory. + /// A object that may contain nested directories and files. + private Directory CreateNestedDirectory(int currentDepth, int maxDepth, int maxChildrenPerDirectory) + { + List childItems = []; + + if (currentDepth < maxDepth) + { + int childCount = _faker.Random.Int(0, maxChildrenPerDirectory); + for (int i = 0; i < childCount; i++) + childItems.Add(CreateNestedDirectory(currentDepth + 1, maxDepth, maxChildrenPerDirectory)); + } + return CreateDirectory(childItems: childItems); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Entities/Fixtures/FileFixture.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Entities/Fixtures/FileFixture.cs new file mode 100644 index 00000000..294baebb --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Entities/Fixtures/FileFixture.cs @@ -0,0 +1,88 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using ErrorOr; +using Lumina.Contracts.Enums.FileSystem; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Entities.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class FileFixture +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly Faker _faker; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public FileFixture() + { + _faker = new Faker(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + /// + /// Creates a random valid . + /// + /// The created . + public File CreateFile( + string? path = null, + string? name = null, + Optional? dateCreated = null, + Optional? dateModified = null, + long? size = null, + FileSystemItemStatus? status = null) + { + path ??= _faker.System.FilePath(); + name ??= _faker.System.FileName(); + dateCreated ??= Optional.Some(_faker.Date.Past()); + dateModified ??= Optional.Some(_faker.Date.Recent()); + size ??= _faker.Random.Long(); + status ??= _faker.PickRandom(); + + ErrorOr fileResult = File.Create(path, name, dateCreated.Value, dateModified.Value, size.Value, status.Value); + + if (fileResult.IsError) + throw new InvalidOperationException("Failed to create File: " + string.Join(", ", fileResult.Errors)); + return fileResult.Value; + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return Enumerable.Range(0, count).Select(_ => CreateFile()).ToList(); + } + + /// + /// Creates a random valid , without creationg and modification dates. + /// + /// + public static File CreateFileWithoutDates() + { + return File.Create( + "/path/to/file_without_dates.txt", + "file_without_dates.txt", + Optional.None(), + Optional.None(), + 2048, + FileSystemItemStatus.Accessible + ).Value; + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Entities/Fixtures/UnixRootItemFixture.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Entities/Fixtures/UnixRootItemFixture.cs new file mode 100644 index 00000000..7ae9bf5f --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Entities/Fixtures/UnixRootItemFixture.cs @@ -0,0 +1,33 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using ErrorOr; +using Lumina.Contracts.Enums.FileSystem; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Entities.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class UnixRootItemFixture +{ + #region ===================================================================== METHODS =================================================================================== + /// + /// Creates a random valid . + /// + /// The status of the UNIX root item. + /// The created . + public UnixRootItem CreateUnixRootItem(FileSystemItemStatus status = FileSystemItemStatus.Accessible) + { + ErrorOr unixRootItemResult = UnixRootItem.Create(status); + + if (unixRootItemResult.IsError) + throw new InvalidOperationException("Failed to create UnixRootItem: " + string.Join(", ", unixRootItemResult.Errors)); + return unixRootItemResult.Value; + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Entities/UnixRootItemTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Entities/UnixRootItemTests.cs new file mode 100644 index 00000000..4c30e575 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Entities/UnixRootItemTests.cs @@ -0,0 +1,106 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FluentAssertions; +using Lumina.Contracts.Enums.FileSystem; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Entities; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UnixRootItemTests +{ + #region ===================================================================== METHODS =================================================================================== + [Fact] + public void Create_WhenCalledWithDefaultStatus_ShouldReturnSuccessfulResult() + { + // Arrange & Act + ErrorOr result = UnixRootItem.Create(); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Name.Should().Be("/"); + result.Value.Id.Path.Should().Be("/"); + result.Value.Type.Should().Be(FileSystemItemType.Root); + result.Value.Status.Should().Be(FileSystemItemStatus.Accessible); + result.Value.Items.Should().BeEmpty(); + } + + [Fact] + public void Create_WhenCalledWithCustomStatus_ShouldReturnSuccessfulResultWithSpecifiedStatus() + { + // Arrange + FileSystemItemStatus customStatus = FileSystemItemStatus.Accessible; + + // Act + ErrorOr result = UnixRootItem.Create(customStatus); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Name.Should().Be("/"); + result.Value.Id.Path.Should().Be("/"); + result.Value.Type.Should().Be(FileSystemItemType.Root); + result.Value.Status.Should().Be(customStatus); + result.Value.Items.Should().BeEmpty(); + } + + [Fact] + public void Items_WhenAccessed_ShouldReturnEmptyReadOnlyCollection() + { + // Arrange + ErrorOr createResult = UnixRootItem.Create(); + createResult.IsError.Should().BeFalse(); + UnixRootItem unixRootItem = createResult.Value; + + // Act + IReadOnlyCollection items = unixRootItem.Items; + + // Assert + items.Should().BeEmpty(); + items.Should().BeAssignableTo>(); + } + + [Fact] + public void SetStatus_WhenCalledWithNewStatus_ShouldUpdateStatus() + { + // Arrange + ErrorOr createResult = UnixRootItem.Create(); + createResult.IsError.Should().BeFalse(); + UnixRootItem unixRootItem = createResult.Value; + FileSystemItemStatus newStatus = FileSystemItemStatus.Accessible; + + // Act + ErrorOr result = unixRootItem.SetStatus(newStatus); + + // Assert + result.IsError.Should().BeFalse(); + unixRootItem.Status.Should().Be(newStatus); + } + + [Fact] + public void SetParent_WhenCalledWithNullParent_ShouldReturnError() + { + // Arrange + ErrorOr createResult = UnixRootItem.Create(); + createResult.IsError.Should().BeFalse(); + UnixRootItem unixRootItem = createResult.Value; + + // Act + ErrorOr result = unixRootItem.SetParent(null!); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.ParentNodeCannotBeNull); + unixRootItem.Parent.HasValue.Should().BeFalse(); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Entities/WindowsRootItemTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Entities/WindowsRootItemTests.cs new file mode 100644 index 00000000..f1df9c47 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Entities/WindowsRootItemTests.cs @@ -0,0 +1,148 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FluentAssertions; +using Lumina.Contracts.Enums.FileSystem; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Entities; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class WindowsRootItemTests +{ + #region ===================================================================== METHODS =================================================================================== + [Fact] + public void Create_WhenCalledWithValidParameters_ShouldReturnSuccessfulResult() + { + // Arrange + string path = "C:\\"; + string name = "C:"; + + // Act + ErrorOr result = WindowsRootItem.Create(path, name); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Name.Should().Be(name); + result.Value.Id.Path.Should().Be(path); + result.Value.Type.Should().Be(FileSystemItemType.Root); + result.Value.Status.Should().Be(FileSystemItemStatus.Accessible); + result.Value.Items.Should().BeEmpty(); + } + + [Fact] + public void Create_WhenCalledWithInvalidPath_ShouldReturnError() + { + // Arrange + string invalidPath = ""; + string name = "Invalid"; + + // Act + ErrorOr result = WindowsRootItem.Create(invalidPath, name); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + } + + [Fact] + public void Create_WhenCalledWithCustomStatus_ShouldReturnSuccessfulResultWithSpecifiedStatus() + { + // Arrange + string path = "D:\\"; + string name = "D:"; + FileSystemItemStatus customStatus = FileSystemItemStatus.Accessible; + + // Act + ErrorOr result = WindowsRootItem.Create(path, name, customStatus); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Name.Should().Be(name); + result.Value.Id.Path.Should().Be(path); + result.Value.Type.Should().Be(FileSystemItemType.Root); + result.Value.Status.Should().Be(customStatus); + } + + [Fact] + public void Create_WhenCalledWithFileSystemPathId_ShouldReturnSuccessfulResult() + { + // Arrange + ErrorOr pathIdResult = FileSystemPathId.Create("E:\\"); + pathIdResult.IsError.Should().BeFalse(); + FileSystemPathId pathId = pathIdResult.Value; + string name = "E:"; + + // Act + ErrorOr result = WindowsRootItem.Create(pathId, name); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Id.Should().Be(pathId); + result.Value.Name.Should().Be(name); + result.Value.Type.Should().Be(FileSystemItemType.Root); + result.Value.Status.Should().Be(FileSystemItemStatus.Accessible); + } + + [Fact] + public void Items_WhenAccessed_ShouldReturnEmptyReadOnlyCollection() + { + // Arrange + ErrorOr createResult = WindowsRootItem.Create("F:\\", "F:"); + createResult.IsError.Should().BeFalse(); + WindowsRootItem windowsRootItem = createResult.Value; + + // Act + IReadOnlyCollection items = windowsRootItem.Items; + + // Assert + items.Should().BeEmpty(); + items.Should().BeAssignableTo>(); + } + + [Fact] + public void SetStatus_WhenCalledWithNewStatus_ShouldUpdateStatus() + { + // Arrange + ErrorOr createResult = WindowsRootItem.Create("G:\\", "G:"); + createResult.IsError.Should().BeFalse(); + WindowsRootItem windowsRootItem = createResult.Value; + FileSystemItemStatus newStatus = FileSystemItemStatus.Accessible; + + // Act + ErrorOr result = windowsRootItem.SetStatus(newStatus); + + // Assert + result.IsError.Should().BeFalse(); + windowsRootItem.Status.Should().Be(newStatus); + } + + [Fact] + public void SetParent_WhenCalledWithNullParent_ShouldReturnError() + { + // Arrange + ErrorOr createResult = WindowsRootItem.Create("H:\\", "H:"); + createResult.IsError.Should().BeFalse(); + WindowsRootItem windowsRootItem = createResult.Value; + + // Act + ErrorOr result = windowsRootItem.SetParent(null!); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.ParentNodeCannotBeNull); + windowsRootItem.Parent.HasValue.Should().BeFalse(); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/FileSystemItemTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/FileSystemItemTests.cs new file mode 100644 index 00000000..36fbcd86 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/FileSystemItemTests.cs @@ -0,0 +1,176 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using AutoFixture.AutoNSubstitute; +using ErrorOr; +using FluentAssertions; +using Lumina.Contracts.Enums.FileSystem; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Fixtures; +using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects.Fixtures; +using System.Diagnostics.CodeAnalysis; +#endregion + + +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class FileSystemItemTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly IFixture _fixture; + private readonly FileSystemPathIdFixture _fileSystemPathIdFixture; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public FileSystemItemTests() + { + _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); + _fileSystemPathIdFixture = new FileSystemPathIdFixture(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public void Constructor_WhenCalled_ShouldSetPropertiesCorrectly() + { + // Arrange + FileSystemPathId id = _fileSystemPathIdFixture.CreateFileSystemPathId(); + string name = "TestItem"; + FileSystemItemType type = FileSystemItemType.File; + + // Act + FileSystemItemFixture item = new(id, name, type); + + // Assert + item.Id.Should().Be(id); + item.Name.Should().Be(name); + item.Type.Should().Be(type); + item.Status.Should().Be(FileSystemItemStatus.Accessible); + item.Parent.Should().Be(Optional.None()); + } + + [Fact] + public void SetStatus_WhenCalled_ShouldUpdateStatusAndReturnUpdated() + { + // Arrange + FileSystemItemFixture item = CreateFileSystemItemFixture(); + FileSystemItemStatus newStatus = FileSystemItemStatus.Inaccessible; + + // Act + ErrorOr result = item.SetStatus(newStatus); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().Be(Result.Updated); + item.Status.Should().Be(newStatus); + } + + [Fact] + public void SetParent_WithValidParent_ShouldUpdateParentAndReturnUpdated() + { + // Arrange + FileSystemItemFixture item = CreateFileSystemItemFixture(); + FileSystemItemFixture parent = CreateFileSystemItemFixture(); + + // Act + ErrorOr result = item.SetParent(parent); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().Be(Result.Updated); + item.Parent.Should().Be(Optional.Some(parent)); + } + + [Fact] + public void SetParent_WithNullParent_ShouldReturnError() + { + // Arrange + FileSystemItemFixture item = CreateFileSystemItemFixture(); + + // Act + ErrorOr result = item.SetParent(null!); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.ParentNodeCannotBeNull); + item.Parent.Should().Be(Optional.None()); + } + + [Fact] + public void Equals_WithSameId_ShouldReturnTrue() + { + // Arrange + FileSystemPathId id = _fileSystemPathIdFixture.CreateFileSystemPathId(); + FileSystemItemFixture item1 = CreateFileSystemItemFixture(id); + FileSystemItemFixture item2 = CreateFileSystemItemFixture(id); + + // Act + bool result = item1.Equals(item2); + + // Assert + result.Should().BeTrue(); + } + + [Fact] + public void Equals_WithDifferentId_ShouldReturnFalse() + { + // Arrange + FileSystemItemFixture item1 = CreateFileSystemItemFixture(); + FileSystemItemFixture item2 = CreateFileSystemItemFixture(); + + // Act + bool result = item1.Equals(item2); + + // Assert + result.Should().BeFalse(); + } + + [Fact] + public void GetHashCode_WithSameId_ShouldReturnSameHashCode() + { + // Arrange + FileSystemPathId id = _fileSystemPathIdFixture.CreateFileSystemPathId(); + FileSystemItemFixture item1 = CreateFileSystemItemFixture(id); + FileSystemItemFixture item2 = CreateFileSystemItemFixture(id); + + // Act + int hashCode1 = item1.GetHashCode(); + int hashCode2 = item2.GetHashCode(); + + // Assert + hashCode1.Should().Be(hashCode2); + } + + [Fact] + public void GetHashCode_WithDifferentId_ShouldReturnDifferentHashCode() + { + // Arrange + FileSystemItemFixture item1 = CreateFileSystemItemFixture(); + FileSystemItemFixture item2 = CreateFileSystemItemFixture(); + + // Act + int hashCode1 = item1.GetHashCode(); + int hashCode2 = item2.GetHashCode(); + + // Assert + hashCode1.Should().NotBe(hashCode2); + } + + private FileSystemItemFixture CreateFileSystemItemFixture(FileSystemPathId? id = null) + { + id ??= _fileSystemPathIdFixture.CreateFileSystemPathId(); + string name = _fixture.Create(); + FileSystemItemType type = _fixture.Create(); + return new FileSystemItemFixture(id, name, type); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Fixtures/FileSystemItemFixture.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Fixtures/FileSystemItemFixture.cs new file mode 100644 index 00000000..b95b8e79 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Fixtures/FileSystemItemFixture.cs @@ -0,0 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Enums.FileSystem; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class FileSystemItemFixture : FileSystemItem +{ + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier for the file system path. + /// The name of the file system item. + /// The type of the file system item. + public FileSystemItemFixture(FileSystemPathId id, string name, FileSystemItemType fileSystemItemType) + : base(id, name, fileSystemItemType) + { + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Services/DirectoryProviderServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Services/DirectoryProviderServiceTests.cs new file mode 100644 index 00000000..6d7a7644 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Services/DirectoryProviderServiceTests.cs @@ -0,0 +1,946 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using AutoFixture.AutoNSubstitute; +using ErrorOr; +using FluentAssertions; +using Lumina.Contracts.Enums.FileSystem; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects.Fixtures; +using NSubstitute; +using NSubstitute.ExceptionExtensions; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.IO.Abstractions; +using System.Linq; +#endregion + +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Services; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DirectoryProviderServiceTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly IFixture _fixture; + private readonly IFileSystem _mockFileSystem; + private readonly IFileSystemPermissionsService _mockFileSystemPermissionsService; + private readonly DirectoryProviderService _sut; + private readonly FileSystemPathIdFixture _fileSystemPathIdFixture; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public DirectoryProviderServiceTests() + { + _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); + _mockFileSystem = Substitute.For(); + _mockFileSystemPermissionsService = Substitute.For(); + _sut = new DirectoryProviderService(_mockFileSystem, _mockFileSystemPermissionsService); + _fileSystemPathIdFixture = new(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public void GetSubdirectoryPaths_WhenUserHasNoAccess_ShouldReturnUnauthorizedAccessError() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); + _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory, false).Returns(false); + + // Act + ErrorOr> result = _sut.GetSubdirectoryPaths(path, false); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess); + } + + [Fact] + public void GetSubdirectoryPaths_WhenUserHasAccess_ShouldReturnSubdirectories() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); + string[] subdirectories = _fixture.CreateMany(3).ToArray(); + _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory, false).Returns(true); + _mockFileSystem.Directory.GetDirectories(path.Path).Returns(subdirectories); + _mockFileSystem.Path.DirectorySeparatorChar.Returns('\\'); + + // Act + ErrorOr> result = _sut.GetSubdirectoryPaths(path, false); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().HaveCount(3); + result.Value.Select(x => x.Path).Should().BeEquivalentTo(subdirectories.Select(x => x + '\\')); + } + + [Fact] + public void GetSubdirectoryPaths_WhenIncludeHiddenElementsIsFalse_ShouldExcludeHiddenDirectories() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); + string[] subdirectories = [@"C:\Visible", @"C:\Hidden"]; + _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory, false).Returns(true); + _mockFileSystem.Directory.GetDirectories(path.Path).Returns(subdirectories); + _mockFileSystem.Path.DirectorySeparatorChar.Returns('\\'); + _mockFileSystem.File.GetAttributes(@"C:\Visible").Returns(FileAttributes.Directory); + _mockFileSystem.File.GetAttributes(@"C:\Hidden").Returns(FileAttributes.Directory | FileAttributes.Hidden); + + // Act + ErrorOr> result = _sut.GetSubdirectoryPaths(path, false); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().HaveCount(1); + result.Value.First().Path.Should().Be(@"C:\Visible\"); + } + + [Fact] + public void GetSubdirectoryPaths_WhenIncludeHiddenElementsIsTrue_ShouldIncludeHiddenDirectories() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); + string[] subdirectories = [@"C:\Visible", @"C:\Hidden"]; + _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory, false).Returns(true); + _mockFileSystem.Directory.GetDirectories(path.Path).Returns(subdirectories); + _mockFileSystem.Path.DirectorySeparatorChar.Returns('\\'); + _mockFileSystem.File.GetAttributes(@"C:\Visible").Returns(FileAttributes.Directory); + _mockFileSystem.File.GetAttributes(@"C:\Hidden").Returns(FileAttributes.Directory | FileAttributes.Hidden); + + // Act + ErrorOr> result = _sut.GetSubdirectoryPaths(path, true); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().HaveCount(2); + result.Value.Select(x => x.Path).Should().BeEquivalentTo([@"C:\Visible\", @"C:\Hidden\"]); + } + + [Fact] + public void GetSubdirectoryPaths_WhenGetAttributesThrowsException_ShouldStillAddDirectory() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); + string[] subdirectories = [@"C:\Valid", @"C:\Invalid"]; + _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory, false).Returns(true); + _mockFileSystem.Directory.GetDirectories(path.Path).Returns(subdirectories); + _mockFileSystem.Path.DirectorySeparatorChar.Returns('\\'); + _mockFileSystem.File.GetAttributes(@"C:\Valid").Returns(FileAttributes.Directory); + _mockFileSystem.File.GetAttributes(@"C:\Invalid").Throws(new Exception("Access denied")); + + // Act + ErrorOr> result = _sut.GetSubdirectoryPaths(path, false); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().HaveCount(2); + result.Value.First().Path.Should().Be(@"C:\Invalid\"); + result.Value.Last().Path.Should().Be(@"C:\Valid\"); + } + + [Fact] + public void GetSubdirectoryPaths_ShouldOrderDirectoriesAlphabetically() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); + string[] subdirectories = [@"C:\C", @"C:\A", @"C:\B"]; + _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory, false).Returns(true); + _mockFileSystem.Directory.GetDirectories(path.Path).Returns(subdirectories); + _mockFileSystem.Path.DirectorySeparatorChar.Returns('\\'); + _mockFileSystem.File.GetAttributes(Arg.Any()).Returns(FileAttributes.Directory); + + // Act + ErrorOr> result = _sut.GetSubdirectoryPaths(path, false); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Select(x => x.Path).Should().BeEquivalentTo([@"C:\A\", @"C:\B\", @"C:\C\"], options => options.WithStrictOrdering()); + } + + [Fact] + public void GetSubdirectoryPaths_WhenDirectoryHasNoSubdirectories_ShouldReturnEmptyList() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); + _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory, false).Returns(true); + _mockFileSystem.Directory.GetDirectories(path.Path).Returns([]); + + // Act + ErrorOr> result = _sut.GetSubdirectoryPaths(path, false); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().BeEmpty(); + } + + [Fact] + public void DirectoryExists_WhenDirectoryExists_ShouldReturnTrue() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); + _mockFileSystem.Directory.Exists(path.Path).Returns(true); + + // Act + ErrorOr result = _sut.DirectoryExists(path); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().BeTrue(); + } + + [Fact] + public void DirectoryExists_WhenDirectoryDoesNotExist_ShouldReturnFalse() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); + _mockFileSystem.Directory.Exists(path.Path).Returns(false); + + // Act + ErrorOr result = _sut.DirectoryExists(path); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().BeFalse(); + } + + [Fact] + public void GetFileName_WhenPathIsValid_ShouldReturnFileName() + { + // Arrange + string fullPath = @"C:\folder\subfolder\file.txt"; + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(fullPath); + _mockFileSystem.Path.GetFileName(fullPath).Returns("file.txt"); + + // Act + ErrorOr result = _sut.GetFileName(path); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().Be("file.txt"); + } + + [Fact] + public void GetFileName_WhenPathEndsWithDirectorySeparator_ShouldReturnLastSegment() + { + // Arrange + string fullPath = @"C:\folder\subfolder\"; + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(fullPath); + _mockFileSystem.Path.GetFileName(fullPath[..^1]).Returns("subfolder"); + _mockFileSystem.Path.DirectorySeparatorChar.Returns('\\'); + + // Act + ErrorOr result = _sut.GetFileName(path); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().Be("subfolder"); + } + + [Fact] + public void GetFileName_WhenPathIsRoot_ShouldReturnEmptyString() + { + // Arrange + string fullPath = @"C:\"; + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(fullPath); + _mockFileSystem.Path.GetFileName(fullPath[..^1]).Returns(string.Empty); + _mockFileSystem.Path.DirectorySeparatorChar.Returns('\\'); + + // Act + ErrorOr result = _sut.GetFileName(path); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().BeEmpty(); + } + + [Fact] + public void GetLastWriteTime_WhenUserHasAccess_ShouldReturnLastWriteTime() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); + DateTime expectedDateTime = DateTime.Now; + _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties, false).Returns(true); + _mockFileSystem.Directory.GetLastWriteTime(path.Path).Returns(expectedDateTime); + + // Act + ErrorOr> result = _sut.GetLastWriteTime(path); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.HasValue.Should().BeTrue(); + result.Value.Value.Should().Be(expectedDateTime); + } + + [Fact] + public void GetLastWriteTime_WhenUserHasNoAccess_ShouldReturnUnauthorizedAccessError() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); + _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties, false).Returns(false); + + // Act + ErrorOr> result = _sut.GetLastWriteTime(path); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess); + } + + [Fact] + public void GetCreationTime_WhenUserHasAccess_ShouldReturnCreationTime() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); + DateTime expectedDateTime = DateTime.Now; + _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties, false).Returns(true); + _mockFileSystem.Directory.GetCreationTime(path.Path).Returns(expectedDateTime); + + // Act + ErrorOr> result = _sut.GetCreationTime(path); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.HasValue.Should().BeTrue(); + result.Value.Value.Should().Be(expectedDateTime); + } + + [Fact] + public void GetCreationTime_WhenUserHasNoAccess_ShouldReturnUnauthorizedAccessError() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); + _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties, false).Returns(false); + + // Act + ErrorOr> result = _sut.GetCreationTime(path); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess); + } + + [Fact] + public void CreateDirectory_WhenUserHasAccess_ShouldCreateDirectoryAndReturnPath() + { + // Arrange + FileSystemPathId parentPath = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Parent"); + string directoryName = "NewDirectory"; + string fullPath = @"C:\Parent\NewDirectory"; + + _mockFileSystemPermissionsService.CanAccessPath(parentPath, FileAccessMode.Write, false).Returns(true); + _mockFileSystem.Path.Combine(parentPath.Path, directoryName).Returns(fullPath); + + IDirectoryInfo mockDirectoryInfo = Substitute.For(); + mockDirectoryInfo.FullName.Returns(fullPath); + _mockFileSystem.Directory.CreateDirectory(fullPath).Returns(mockDirectoryInfo); + + // Act + ErrorOr result = _sut.CreateDirectory(parentPath, directoryName); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Path.Should().Be(fullPath); + _mockFileSystem.Directory.Received(1).CreateDirectory(fullPath); + } + + [Fact] + public void CreateDirectory_WhenUserHasNoAccess_ShouldReturnUnauthorizedAccessError() + { + // Arrange + FileSystemPathId parentPath = _fileSystemPathIdFixture.CreateFileSystemPathId(); + string directoryName = "NewDirectory"; + + _mockFileSystemPermissionsService.CanAccessPath(parentPath, FileAccessMode.Write, false).Returns(false); + + // Act + ErrorOr result = _sut.CreateDirectory(parentPath, directoryName); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess); + _mockFileSystem.Directory.DidNotReceive().CreateDirectory(Arg.Any()); + } + + [Fact] + public void CreateDirectory_WhenParentPathIsNull_ShouldReturnError() + { + // Arrange + FileSystemPathId parentPath = null!; + string directoryName = "NewDirectory"; + + // Act + ErrorOr result = _sut.CreateDirectory(parentPath, directoryName); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Type.Should().Be(ErrorType.Failure); + } + + [Fact] + public void CreateDirectory_WhenCreatedDirectoryPathIsInvalid_ShouldReturnError() + { + // Arrange + FileSystemPathId parentPath = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Parent"); + string directoryName = "NewDirectory"; + string invalidPath = "Invalid:Path"; + + _mockFileSystemPermissionsService.CanAccessPath(parentPath, FileAccessMode.Write, false).Returns(true); + _mockFileSystem.Path.Combine(parentPath.Path, directoryName).Returns(invalidPath); + _mockFileSystem.Directory.CreateDirectory(invalidPath).Returns(Substitute.For()); + + // Act + ErrorOr result = _sut.CreateDirectory(parentPath, directoryName); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Type.Should().Be(ErrorType.Validation); + } + + [Fact] + public void CopyDirectory_WhenSourceDirectoryExistsAndUserHasAccess_ShouldCopyDirectoryAndReturnPath() + { + // Arrange + FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Source"); + FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Destination"); + bool overrideExisting = false; + + _mockFileSystem.Directory.Exists(sourcePath.Path).Returns(true); + _mockFileSystem.Directory.Exists(destinationPath.Path).Returns(false); + _mockFileSystem.Directory.CreateDirectory(destinationPath.Path).Returns(Substitute.For()); + + IDirectoryInfo sourceDirectoryInfo = Substitute.For(); + sourceDirectoryInfo.GetFiles().Returns([]); + sourceDirectoryInfo.GetDirectories().Returns([]); + _mockFileSystem.DirectoryInfo.New(sourcePath.Path).Returns(sourceDirectoryInfo); + + _mockFileSystem.Path.Combine(Arg.Any(), Arg.Any()) + .Returns(callInfo => Path.Combine(callInfo.ArgAt(0), callInfo.ArgAt(1))); + + // Act + ErrorOr result = _sut.CopyDirectory(sourcePath, destinationPath, overrideExisting); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Path.Should().Be(destinationPath.Path); + _mockFileSystem.Directory.Received(1).CreateDirectory(destinationPath.Path); + } + + [Fact] + public void CopyDirectory_WhenSourceDirectoryDoesNotExist_ShouldReturnError() + { + // Arrange + FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId(); + FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(); + bool overrideExisting = false; + + _mockFileSystem.Directory.Exists(sourcePath.Path).Returns(false); + + // Act + ErrorOr result = _sut.CopyDirectory(sourcePath, destinationPath, overrideExisting); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.DirectoryNotFound); + } + + [Fact] + public void CopyDirectory_WhenDestinationDirectoryExists_ShouldCreateUniqueDirectoryName() + { + // Arrange + FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Source"); + FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Destination"); + string expectedNewDirectoryPath = @"C:\Destination - Copy (1)"; + bool overrideExisting = false; + + _mockFileSystem.Directory.Exists(sourcePath.Path).Returns(true); + _mockFileSystem.Directory.Exists(destinationPath.Path).Returns(true); + _mockFileSystem.Directory.Exists(@"C:\Destination").Returns(true); + _mockFileSystem.Directory.Exists(expectedNewDirectoryPath).Returns(false); + _mockFileSystem.Directory.CreateDirectory(expectedNewDirectoryPath).Returns(Substitute.For()); + + IDirectoryInfo sourceDirectoryInfo = Substitute.For(); + sourceDirectoryInfo.GetFiles().Returns([]); + sourceDirectoryInfo.GetDirectories().Returns([]); + _mockFileSystem.DirectoryInfo.New(sourcePath.Path).Returns(sourceDirectoryInfo); + + _mockFileSystem.Path.Combine(Arg.Any(), Arg.Any()) + .Returns(callInfo => Path.Combine(callInfo.ArgAt(0), callInfo.ArgAt(1))); + + // Act + ErrorOr result = _sut.CopyDirectory(sourcePath, destinationPath, overrideExisting); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Path.Should().Be(expectedNewDirectoryPath); + _mockFileSystem.Directory.Received(1).CreateDirectory(expectedNewDirectoryPath); + } + + [Fact] + public void CopyDirectory_WhenCopyingFilesAndSubdirectories_ShouldCopyAllContents() + { + // Arrange + FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Source"); + FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Destination"); + bool overrideExisting = true; + + // ensure all relevant directories exist + _mockFileSystem.Directory.Exists(@"C:\Source").Returns(true); + _mockFileSystem.Directory.Exists(@"C:\Source\SubDir").Returns(true); + _mockFileSystem.Directory.Exists(@"C:\Destination").Returns(false); + _mockFileSystem.Directory.CreateDirectory(Arg.Any()).Returns(callInfo => { + IDirectoryInfo mockDirInfo = Substitute.For(); + mockDirInfo.FullName.Returns(callInfo.Arg()); + return mockDirInfo; + }); + + IFileInfo mockFile = Substitute.For(); + mockFile.Name.Returns("file.txt"); + mockFile.Attributes.Returns(FileAttributes.Normal); + + IDirectoryInfo mockSubDir = Substitute.For(); + mockSubDir.Name.Returns("SubDir"); + mockSubDir.FullName.Returns(@"C:\Source\SubDir"); + + IDirectoryInfo sourceDirectoryInfo = Substitute.For(); + sourceDirectoryInfo.GetFiles().Returns([mockFile]); + sourceDirectoryInfo.GetDirectories().Returns([mockSubDir]); + _mockFileSystem.DirectoryInfo.New(@"C:\Source").Returns(sourceDirectoryInfo); + + // mock subdirectory info + IDirectoryInfo subDirInfo = Substitute.For(); + subDirInfo.GetFiles().Returns([]); + subDirInfo.GetDirectories().Returns([]); + _mockFileSystem.DirectoryInfo.New(@"C:\Source\SubDir").Returns(subDirInfo); + + // mock the Path.Combine method for all necessary cases + _mockFileSystem.Path.Combine(Arg.Any(), Arg.Any()) + .Returns(callInfo => Path.Combine(callInfo.ArgAt(0), callInfo.ArgAt(1))); + + // Act + ErrorOr result = _sut.CopyDirectory(sourcePath, destinationPath, overrideExisting); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Path.Should().Be(@"C:\Destination"); + _mockFileSystem.Directory.Received(1).CreateDirectory(@"C:\Destination"); + _mockFileSystem.Directory.Received(1).CreateDirectory(@"C:\Destination\SubDir"); + mockFile.Received(1).CopyTo(@"C:\Destination\file.txt", overrideExisting); + _mockFileSystem.File.Received(1).SetAttributes(@"C:\Destination\file.txt", FileAttributes.Normal); + } + + [Fact] + public void CopyDirectory_WhenExceptionOccurs_ShouldReturnError() + { + // Arrange + FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId(); + FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(); + bool overrideExisting = false; + + _mockFileSystem.Directory.Exists(sourcePath.Path).Returns(true); + _mockFileSystem.Directory.CreateDirectory(Arg.Any()).Throws(new Exception("Simulated error")); + + // Act + ErrorOr result = _sut.CopyDirectory(sourcePath, destinationPath, overrideExisting); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.DirectoryCopyError); + } + + [Fact] + public void MoveDirectory_WhenSourceDirectoryDoesNotExist_ShouldReturnDirectoryNotFoundError() + { + // Arrange + FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\NonExistentSource"); + FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Destination"); + bool overrideExisting = false; + + _mockFileSystem.Directory.Exists(sourcePath.Path).Returns(false); + + // Act + ErrorOr result = _sut.MoveDirectory(sourcePath, destinationPath, overrideExisting); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.DirectoryNotFound); + } + + [Fact] + public void MoveDirectory_WhenDestinationDirectoryDoesNotExist_ShouldPerformSimpleMove() + { + // Arrange + FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Source"); + FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Destination"); + bool overrideExisting = false; + + _mockFileSystem.Directory.Exists(sourcePath.Path).Returns(true); + _mockFileSystem.Directory.Exists(destinationPath.Path).Returns(false); + + // Act + ErrorOr result = _sut.MoveDirectory(sourcePath, destinationPath, overrideExisting); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Path.Should().Be(destinationPath.Path); + _mockFileSystem.Directory.Received(1).Move(sourcePath.Path, destinationPath.Path); + } + + [Fact] + public void MoveDirectory_WhenDestinationDirectoryExists_ShouldMergeDirectories() + { + // Arrange + FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Source"); + FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Destination"); + bool overrideExisting = true; + + _mockFileSystem.Directory.Exists(sourcePath.Path).Returns(true); + _mockFileSystem.Directory.Exists(destinationPath.Path).Returns(true); + + _mockFileSystem.Directory.GetFiles(sourcePath.Path).Returns([@"C:\Source\file1.txt"]); + _mockFileSystem.Directory.GetDirectories(sourcePath.Path).Returns([@"C:\Source\SubDir"]); + + _mockFileSystem.Directory.GetFiles(@"C:\Source\SubDir").Returns([]); + _mockFileSystem.Directory.GetDirectories(@"C:\Source\SubDir").Returns([]); + + _mockFileSystem.Path.GetFileName(@"C:\Source\file1.txt").Returns("file1.txt"); + _mockFileSystem.Path.GetFileName(@"C:\Source\SubDir").Returns("SubDir"); + + _mockFileSystem.Path.Combine(Arg.Any(), Arg.Any()) + .Returns(callInfo => Path.Combine(callInfo.ArgAt(0), callInfo.ArgAt(1))); + + _mockFileSystem.Directory.EnumerateFileSystemEntries(sourcePath.Path).Returns([]); + + // Act + ErrorOr result = _sut.MoveDirectory(sourcePath, destinationPath, overrideExisting); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Path.Should().Be(destinationPath.Path); + _mockFileSystem.File.Received(1).Move(@"C:\Source\file1.txt", @"C:\Destination\file1.txt"); + _mockFileSystem.Directory.Received(1).Move(@"C:\Source\SubDir", @"C:\Destination\SubDir"); + _mockFileSystem.Directory.Received(1).Delete(sourcePath.Path); + } + + [Fact] + public void MoveDirectory_WhenExceptionOccurs_ShouldReturnDirectoryMoveError() + { + // Arrange + FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Source"); + FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Destination"); + bool overrideExisting = false; + + _mockFileSystem.Directory.Exists(sourcePath.Path).Returns(true); + _mockFileSystem.Directory.Exists(destinationPath.Path).Returns(false); + _mockFileSystem.Directory.When(x => x.Move(Arg.Any(), Arg.Any())) + .Do(x => throw new IOException("Simulated IO error")); + + // Act + ErrorOr result = _sut.MoveDirectory(sourcePath, destinationPath, overrideExisting); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.DirectoryMoveError); + } + + [Fact] + public void MergeDirectories_WhenSourceContainsFilesAndSubdirectories_ShouldMergeCorrectly() + { + // Arrange + FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Source"); + FileSystemPathId destPath = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Destination"); + bool overwrite = true; + + _mockFileSystem.Directory.Exists(sourcePath.Path).Returns(true); + _mockFileSystem.Directory.Exists(destPath.Path).Returns(true); + + _mockFileSystem.Directory.GetFiles(sourcePath.Path).Returns([@"C:\Source\file1.txt", @"C:\Source\file2.txt"]); + _mockFileSystem.Directory.GetDirectories(sourcePath.Path).Returns([@"C:\Source\SubDir1", @"C:\Source\SubDir2"]); + + _mockFileSystem.Path.GetFileName(@"C:\Source\file1.txt").Returns("file1.txt"); + _mockFileSystem.Path.GetFileName(@"C:\Source\file2.txt").Returns("file2.txt"); + _mockFileSystem.Path.GetFileName(@"C:\Source\SubDir1").Returns("SubDir1"); + _mockFileSystem.Path.GetFileName(@"C:\Source\SubDir2").Returns("SubDir2"); + + _mockFileSystem.File.Exists(@"C:\Destination\file1.txt").Returns(true); + _mockFileSystem.File.Exists(@"C:\Destination\file2.txt").Returns(false); + + _mockFileSystem.Directory.Exists(@"C:\Destination\SubDir1").Returns(true); + _mockFileSystem.Directory.Exists(@"C:\Destination\SubDir2").Returns(false); + + _mockFileSystem.Path.Combine(Arg.Any(), Arg.Any()) + .Returns(callInfo => Path.Combine(callInfo.ArgAt(0), callInfo.ArgAt(1))); + + _mockFileSystem.Directory.EnumerateFileSystemEntries(sourcePath.Path).Returns([]); + + // Act + ErrorOr result = _sut.MoveDirectory(sourcePath, destPath, overwrite); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().Be(destPath); + _mockFileSystem.File.Received(1).Delete(@"C:\Destination\file1.txt"); + _mockFileSystem.File.Received(1).Move(@"C:\Source\file1.txt", @"C:\Destination\file1.txt"); + _mockFileSystem.File.Received(1).Move(@"C:\Source\file2.txt", @"C:\Destination\file2.txt"); + _mockFileSystem.Directory.Received(1).Move(@"C:\Source\SubDir2", @"C:\Destination\SubDir2"); + _mockFileSystem.Directory.Received(1).Delete(sourcePath.Path); + } + + [Fact] + public void MoveDirectory_WhenOverwriteIsFalse_ShouldMoveOnlyNonExistingFiles() + { + // Arrange + FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Source"); + FileSystemPathId destPath = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Destination"); + bool overwrite = false; + + _mockFileSystem.Directory.Exists(sourcePath.Path).Returns(true); + _mockFileSystem.Directory.Exists(destPath.Path).Returns(true); + + _mockFileSystem.Directory.GetFiles(sourcePath.Path).Returns([@"C:\Source\file1.txt", @"C:\Source\file2.txt"]); + _mockFileSystem.Directory.GetDirectories(sourcePath.Path).Returns([]); + + _mockFileSystem.Path.GetFileName(@"C:\Source\file1.txt").Returns("file1.txt"); + _mockFileSystem.Path.GetFileName(@"C:\Source\file2.txt").Returns("file2.txt"); + + _mockFileSystem.File.Exists(@"C:\Destination\file1.txt").Returns(true); + _mockFileSystem.File.Exists(@"C:\Destination\file2.txt").Returns(false); + + _mockFileSystem.Path.Combine(Arg.Any(), Arg.Any()) + .Returns(callInfo => Path.Combine(callInfo.ArgAt(0), callInfo.ArgAt(1))); + + _mockFileSystem.Directory.EnumerateFileSystemEntries(sourcePath.Path).Returns([@"C:\Source\file2.txt"]); + + // Act + ErrorOr result = _sut.MoveDirectory(sourcePath, destPath, overwrite); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().Be(destPath); + _mockFileSystem.File.DidNotReceive().Delete(Arg.Any()); + _mockFileSystem.File.DidNotReceive().Move(@"C:\Source\file1.txt", @"C:\Destination\file1.txt"); + _mockFileSystem.File.Received(1).Move(@"C:\Source\file2.txt", @"C:\Destination\file2.txt"); + _mockFileSystem.Directory.DidNotReceive().Delete(sourcePath.Path); + } + + [Fact] + public void MergeDirectories_WhenSourceIsEmpty_ShouldDeleteSourceDirectory() + { + // Arrange + string sourceDir = @"C:\Source"; + string destDir = @"C:\Destination"; + bool overwrite = true; + + _mockFileSystem.Directory.GetFiles(sourceDir).Returns([]); + _mockFileSystem.Directory.GetDirectories(sourceDir).Returns([]); + _mockFileSystem.Directory.EnumerateFileSystemEntries(sourceDir).Returns([]); + _mockFileSystem.Directory.Exists(sourceDir).Returns(true); + _mockFileSystem.Directory.Exists(destDir).Returns(true); + + // Act + _sut.MoveDirectory(FileSystemPathId.Create(sourceDir).Value, FileSystemPathId.Create(destDir).Value, overwrite); + + // Assert + _mockFileSystem.Directory.Received(1).Delete(sourceDir); + } + + [Fact] + public void MergeDirectories_WhenSourceContainsNestedDirectories_ShouldMergeRecursively() + { + // Arrange + FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Source"); + FileSystemPathId destPath = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Destination"); + bool overwrite = true; + + _mockFileSystem.Directory.Exists(sourcePath.Path).Returns(true); + _mockFileSystem.Directory.Exists(destPath.Path).Returns(true); + + _mockFileSystem.Directory.Exists(@"C:\Source\SubDir").Returns(true); + _mockFileSystem.Directory.Exists(@"C:\Destination\SubDir").Returns(true); + + _mockFileSystem.Directory.GetFiles(sourcePath.Path).Returns([]); + _mockFileSystem.Directory.GetDirectories(sourcePath.Path).Returns([@"C:\Source\SubDir"]); + + _mockFileSystem.Directory.GetFiles(@"C:\Source\SubDir").Returns([@"C:\Source\SubDir\file.txt"]); + _mockFileSystem.Directory.GetDirectories(@"C:\Source\SubDir").Returns([]); + + _mockFileSystem.Path.GetFileName(@"C:\Source\SubDir").Returns("SubDir"); + _mockFileSystem.Path.GetFileName(@"C:\Source\SubDir\file.txt").Returns("file.txt"); + + _mockFileSystem.File.Exists(@"C:\Destination\SubDir\file.txt").Returns(false); + + _mockFileSystem.Path.Combine(Arg.Any(), Arg.Any()) + .Returns(callInfo => Path.Combine(callInfo.ArgAt(0), callInfo.ArgAt(1))); + + _mockFileSystem.Directory.EnumerateFileSystemEntries(sourcePath.Path).Returns([@"C:\Source\SubDir"]); + _mockFileSystem.Directory.EnumerateFileSystemEntries(@"C:\Source\SubDir").Returns([]); + + // Act + ErrorOr result = _sut.MoveDirectory(sourcePath, destPath, overwrite); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().Be(destPath); + _mockFileSystem.File.Received(1).Move(@"C:\Source\SubDir\file.txt", @"C:\Destination\SubDir\file.txt"); + _mockFileSystem.Directory.Received(1).Delete(@"C:\Source\SubDir"); + _mockFileSystem.Directory.DidNotReceive().Delete(sourcePath.Path); + } + + [Fact] + public void RenameDirectory_WhenParentDirectoryIsWritable_ShouldRenameSuccessfully() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\OldName"); + string newName = "NewName"; + string parentPath = @"C:\"; + string newPath = @"C:\NewName"; + + IDirectoryInfo parentDirectoryInfo = Substitute.For(); + parentDirectoryInfo.FullName.Returns(parentPath); + _mockFileSystem.Directory.GetParent(path.Path).Returns(parentDirectoryInfo); + _mockFileSystem.Path.Combine(parentPath, newName).Returns(newPath); + _mockFileSystemPermissionsService.CanAccessPath(Arg.Any(), FileAccessMode.Write, false).Returns(true); + _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Execute, false).Returns(true); + + // Act + ErrorOr result = _sut.RenameDirectory(path, newName); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Path.Should().Be(newPath); + _mockFileSystem.Directory.Received(1).Move(path.Path, newPath); + } + + [Fact] + public void RenameDirectory_WhenParentDirectoryIsNotWritable_ShouldReturnUnauthorizedAccessError() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\OldName"); + string newName = "NewName"; + string parentPath = @"C:\"; + string newPath = @"C:\NewName"; + + IDirectoryInfo parentDirectoryInfo = Substitute.For(); + parentDirectoryInfo.FullName.Returns(parentPath); + _mockFileSystem.Directory.GetParent(path.Path).Returns(parentDirectoryInfo); + _mockFileSystem.Path.Combine(parentPath, newName).Returns(newPath); + _mockFileSystemPermissionsService.CanAccessPath(Arg.Any(), FileAccessMode.Write, false).Returns(false); + + // Act + ErrorOr result = _sut.RenameDirectory(path, newName); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess); + _mockFileSystem.Directory.DidNotReceive().Move(Arg.Any(), Arg.Any()); + } + + [Fact] + public void RenameDirectory_WhenDirectoryIsNotExecutable_ShouldReturnUnauthorizedAccessError() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\OldName"); + string newName = "NewName"; + string parentPath = @"C:\"; + string newPath = @"C:\NewName"; + + IDirectoryInfo parentDirectoryInfo = Substitute.For(); + parentDirectoryInfo.FullName.Returns(parentPath); + _mockFileSystem.Directory.GetParent(path.Path).Returns(parentDirectoryInfo); + _mockFileSystem.Path.Combine(parentPath, newName).Returns(newPath); + _mockFileSystemPermissionsService.CanAccessPath(Arg.Any(), FileAccessMode.Write, false).Returns(true); + _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Execute, false).Returns(false); + + // Act + ErrorOr result = _sut.RenameDirectory(path, newName); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess); + _mockFileSystem.Directory.DidNotReceive().Move(Arg.Any(), Arg.Any()); + } + + [Fact] + public void RenameDirectory_WhenParentDirectoryIsNull_ShouldReturnInvalidPathError() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\OldName"); + string newName = "NewName"; + + _mockFileSystem.Directory.GetParent(path.Path).Returns((IDirectoryInfo)null!); + + // Act + ErrorOr result = _sut.RenameDirectory(path, newName); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + _mockFileSystem.Directory.DidNotReceive().Move(Arg.Any(), Arg.Any()); + } + + [Fact] + public void RenameDirectory_WhenNewPathIsInvalid_ShouldReturnInvalidPathError() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\OldName"); + string newName = "NewName"; + string parentPath = @"C:\"; + + IDirectoryInfo parentDirectoryInfo = Substitute.For(); + parentDirectoryInfo.FullName.Returns(parentPath); + _mockFileSystem.Directory.GetParent(path.Path).Returns(parentDirectoryInfo); + _mockFileSystem.Path.Combine(parentPath, newName).Returns((string)null!); + + // Act + ErrorOr result = _sut.RenameDirectory(path, newName); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + _mockFileSystem.Directory.DidNotReceive().Move(Arg.Any(), Arg.Any()); + } + + [Fact] + public void DeleteDirectory_WhenDirectoryExistsAndHasDeletePermission_ShouldDeleteSuccessfully() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\DirectoryToDelete"); + _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Delete, false).Returns(true); + IDirectoryInfo mockDirectoryInfo = Substitute.For(); + _mockFileSystem.DirectoryInfo.New(path.Path).Returns(mockDirectoryInfo); + + // Act + ErrorOr result = _sut.DeleteDirectory(path); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().Be(Result.Deleted); + mockDirectoryInfo.Received(1).Delete(true); + } + + [Fact] + public void DeleteDirectory_WhenNoDeletePermission_ShouldReturnUnauthorizedAccessError() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\DirectoryToDelete"); + _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Delete, false).Returns(false); + + // Act + ErrorOr result = _sut.DeleteDirectory(path); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess); + _mockFileSystem.DirectoryInfo.DidNotReceive().New(Arg.Any()); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Services/DirectoryServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Services/DirectoryServiceTests.cs new file mode 100644 index 00000000..0fd3051d --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Services/DirectoryServiceTests.cs @@ -0,0 +1,750 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FluentAssertions; +using Lumina.Contracts.Enums.FileSystem; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Environment; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Entities.Fixtures; +using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects.Fixtures; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Services; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DirectoryServiceTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly IEnvironmentContext _mockEnvironmentContext; + private readonly IPlatformContextManager _mockPlatformContextManager; + private readonly IPlatformContext _mockPlatformContext; + private readonly DirectoryService _sut; + private readonly FileSystemPathIdFixture _fileSystemPathIdFixture; + private readonly DirectoryFixture _directoryFixture; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public DirectoryServiceTests() + { + _mockEnvironmentContext = Substitute.For(); + _mockPlatformContextManager = Substitute.For(); + _mockPlatformContext = Substitute.For(); + _mockPlatformContextManager.GetCurrentContext().Returns(_mockPlatformContext); + _sut = new DirectoryService(_mockEnvironmentContext, _mockPlatformContextManager); + _fileSystemPathIdFixture = new FileSystemPathIdFixture(); + _directoryFixture = new DirectoryFixture(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public void GetSubdirectories_WithValidPath_ShouldReturnListOfDirectories() + { + // Arrange + string path = @"C:\TestDir"; + bool includeHiddenElements = false; + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); + FileSystemPathId[] subPaths = + [ + _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir\Sub1"), + _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir\Sub2") + ]; + + _mockEnvironmentContext.DirectoryProviderService.GetSubdirectoryPaths(pathId, includeHiddenElements) + .Returns(ErrorOrFactory.From(subPaths.AsEnumerable())); + + foreach (FileSystemPathId subPath in subPaths) + { + _mockEnvironmentContext.DirectoryProviderService.GetFileName(subPath) + .Returns(ErrorOrFactory.From(System.IO.Path.GetFileName(subPath.Path))); + _mockEnvironmentContext.DirectoryProviderService.GetLastWriteTime(subPath) + .Returns(ErrorOrFactory.From(Optional.FromNullable(DateTime.Now))); + _mockEnvironmentContext.DirectoryProviderService.GetCreationTime(subPath) + .Returns(ErrorOrFactory.From(Optional.FromNullable(DateTime.Now.AddDays(-1)))); + } + + // Act + ErrorOr> result = _sut.GetSubdirectories(path, includeHiddenElements); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().HaveCount(2); + result.Value.Select(d => d.Name).Should().BeEquivalentTo(["Sub1", "Sub2"]); + } + + [Fact] + public void GetSubdirectories_WithInvalidPath_ShouldReturnError() + { + // Arrange + string invalidPath = string.Empty; + bool includeHiddenElements = false; + + // Act + ErrorOr> result = _sut.GetSubdirectories(invalidPath, includeHiddenElements); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + } + + [Fact] + public void GetSubdirectories_WhenDirectoryProviderServiceReturnsError_ShouldPropagateError() + { + // Arrange + string path = @"C:\TestDir"; + bool includeHiddenElements = false; + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); + + _mockEnvironmentContext.DirectoryProviderService.GetSubdirectoryPaths(pathId, includeHiddenElements) + .Returns(Errors.Permission.UnauthorizedAccess); + + // Act + ErrorOr> result = _sut.GetSubdirectories(path, includeHiddenElements); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess); + } + + [Fact] + public void GetSubdirectories_WhenSubdirectoryDetailsAreInaccessible_ShouldReturnInaccessibleDirectory() + { + // Arrange + string path = @"C:\TestDir"; + bool includeHiddenElements = false; + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); + FileSystemPathId subPath = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir\InaccessibleSub"); + + _mockEnvironmentContext.DirectoryProviderService.GetSubdirectoryPaths(pathId, includeHiddenElements) + .Returns(ErrorOrFactory.From(new[] { subPath }.AsEnumerable())); + + _mockEnvironmentContext.DirectoryProviderService.GetFileName(subPath) + .Returns(Errors.Permission.UnauthorizedAccess); + _mockEnvironmentContext.DirectoryProviderService.GetLastWriteTime(subPath) + .Returns(Errors.Permission.UnauthorizedAccess); + _mockEnvironmentContext.DirectoryProviderService.GetCreationTime(subPath) + .Returns(Errors.Permission.UnauthorizedAccess); + + // Act + ErrorOr> result = _sut.GetSubdirectories(path, includeHiddenElements); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().HaveCount(1); + result.Value.First().Status.Should().Be(FileSystemItemStatus.Inaccessible); + } + + [Fact] + public void GetSubdirectoriesOverload_WithValidDirectory_ShouldReturnListOfDirectories() + { + // Arrange + Directory parentDirectory = _directoryFixture.CreateDirectory(); + bool includeHiddenElements = false; + FileSystemPathId[] subPaths = + [ + _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir\Sub1"), + _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir\Sub2") + ]; + + _mockEnvironmentContext.DirectoryProviderService.GetSubdirectoryPaths(parentDirectory.Id, includeHiddenElements) + .Returns(ErrorOrFactory.From(subPaths.AsEnumerable())); + + foreach (FileSystemPathId subPath in subPaths) + { + _mockEnvironmentContext.DirectoryProviderService.GetFileName(subPath) + .Returns(ErrorOrFactory.From(System.IO.Path.GetFileName(subPath.Path))); + _mockEnvironmentContext.DirectoryProviderService.GetLastWriteTime(subPath) + .Returns(ErrorOrFactory.From(Optional.FromNullable(DateTime.Now))); + _mockEnvironmentContext.DirectoryProviderService.GetCreationTime(subPath) + .Returns(ErrorOrFactory.From(Optional.FromNullable(DateTime.Now.AddDays(-1)))); + } + + // Act + ErrorOr> result = _sut.GetSubdirectories(parentDirectory, includeHiddenElements); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().HaveCount(2); + result.Value.Select(d => d.Name).Should().BeEquivalentTo(["Sub1", "Sub2"]); + } + + [Fact] + public void GetSubdirectoriesOverload_WhenDirectoryProviderServiceReturnsError_ShouldPropagateError() + { + // Arrange + Directory parentDirectory = _directoryFixture.CreateDirectory(); + bool includeHiddenElements = false; + + _mockEnvironmentContext.DirectoryProviderService.GetSubdirectoryPaths(parentDirectory.Id, includeHiddenElements) + .Returns(Errors.Permission.UnauthorizedAccess); + + // Act + ErrorOr> result = _sut.GetSubdirectories(parentDirectory, includeHiddenElements); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess); + } + + [Fact] + public void GetSubdirectoriesOverload_WhenSubdirectoryDetailsAreInaccessible_ShouldReturnInaccessibleDirectory() + { + // Arrange + Directory parentDirectory = _directoryFixture.CreateDirectory(); + bool includeHiddenElements = false; + FileSystemPathId subPath = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir\InaccessibleSub"); + + _mockEnvironmentContext.DirectoryProviderService.GetSubdirectoryPaths(parentDirectory.Id, includeHiddenElements) + .Returns(ErrorOrFactory.From(new[] { subPath }.AsEnumerable())); + + _mockEnvironmentContext.DirectoryProviderService.GetFileName(subPath) + .Returns(Errors.Permission.UnauthorizedAccess); + _mockEnvironmentContext.DirectoryProviderService.GetLastWriteTime(subPath) + .Returns(Errors.Permission.UnauthorizedAccess); + _mockEnvironmentContext.DirectoryProviderService.GetCreationTime(subPath) + .Returns(Errors.Permission.UnauthorizedAccess); + + // Act + ErrorOr> result = _sut.GetSubdirectories(parentDirectory, includeHiddenElements); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().HaveCount(1); + result.Value.First().Status.Should().Be(FileSystemItemStatus.Inaccessible); + } + + [Fact] + public void GetSubdirectories_WithValidFileSystemPathId_ShouldReturnListOfDirectories() + { + // Arrange + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir"); + bool includeHiddenElements = false; + FileSystemPathId[] subPaths = + [ + _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir\Sub1"), + _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir\Sub2") + ]; + + _mockEnvironmentContext.DirectoryProviderService.GetSubdirectoryPaths(pathId, includeHiddenElements) + .Returns(ErrorOrFactory.From(subPaths.AsEnumerable())); + + foreach (FileSystemPathId subPath in subPaths) + { + _mockEnvironmentContext.DirectoryProviderService.GetFileName(subPath) + .Returns(ErrorOrFactory.From(System.IO.Path.GetFileName(subPath.Path))); + _mockEnvironmentContext.DirectoryProviderService.GetLastWriteTime(subPath) + .Returns(ErrorOrFactory.From(Optional.FromNullable(DateTime.Now))); + _mockEnvironmentContext.DirectoryProviderService.GetCreationTime(subPath) + .Returns(ErrorOrFactory.From(Optional.FromNullable(DateTime.Now.AddDays(-1)))); + } + + // Act + ErrorOr> result = _sut.GetSubdirectories(pathId, includeHiddenElements); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().HaveCount(2); + result.Value.Select(d => d.Name).Should().BeEquivalentTo(["Sub1", "Sub2"]); + } + + [Fact] + public void GetSubdirectoriesWithFileSystemPathId_WhenDirectoryProviderServiceReturnsError_ShouldPropagateError() + { + // Arrange + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir"); + bool includeHiddenElements = false; + + _mockEnvironmentContext.DirectoryProviderService.GetSubdirectoryPaths(pathId, includeHiddenElements) + .Returns(Errors.Permission.UnauthorizedAccess); + + // Act + ErrorOr> result = _sut.GetSubdirectories(pathId, includeHiddenElements); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess); + } + + [Fact] + public void GetSubdirectoriesWithFileSystemPathId_WhenSubdirectoryDetailsAreInaccessible_ShouldReturnInaccessibleDirectory() + { + // Arrange + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir"); + bool includeHiddenElements = false; + FileSystemPathId subPath = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir\InaccessibleSub"); + + _mockEnvironmentContext.DirectoryProviderService.GetSubdirectoryPaths(pathId, includeHiddenElements) + .Returns(ErrorOrFactory.From(new[] { subPath }.AsEnumerable())); + + _mockEnvironmentContext.DirectoryProviderService.GetFileName(subPath) + .Returns(Errors.Permission.UnauthorizedAccess); + _mockEnvironmentContext.DirectoryProviderService.GetLastWriteTime(subPath) + .Returns(Errors.Permission.UnauthorizedAccess); + _mockEnvironmentContext.DirectoryProviderService.GetCreationTime(subPath) + .Returns(Errors.Permission.UnauthorizedAccess); + + // Act + ErrorOr> result = _sut.GetSubdirectories(pathId, includeHiddenElements); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().HaveCount(1); + result.Value.First().Status.Should().Be(FileSystemItemStatus.Inaccessible); + } + + [Fact] + public void CreateDirectory_WithValidStringPath_ShouldReturnNewDirectory() + { + // Arrange + string parentPath = @"C:\TestDir"; + string newDirName = "NewDirectory"; + FileSystemPathId parentPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(parentPath); + FileSystemPathId newDirPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(System.IO.Path.Combine(parentPath, newDirName)); + + _mockEnvironmentContext.DirectoryProviderService.CreateDirectory(parentPathId, newDirName) + .Returns(ErrorOrFactory.From(newDirPathId)); + _mockEnvironmentContext.DirectoryProviderService.GetFileName(newDirPathId) + .Returns(ErrorOrFactory.From(newDirName)); + _mockEnvironmentContext.DirectoryProviderService.GetLastWriteTime(newDirPathId) + .Returns(ErrorOrFactory.From(Optional.FromNullable(DateTime.Now))); + _mockEnvironmentContext.DirectoryProviderService.GetCreationTime(newDirPathId) + .Returns(ErrorOrFactory.From(Optional.FromNullable(DateTime.Now))); + + // Act + ErrorOr result = _sut.CreateDirectory(parentPath, newDirName); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Id.Should().Be(newDirPathId); + } + + [Fact] + public void CreateDirectory_WithInvalidStringPath_ShouldReturnError() + { + // Arrange + string invalidPath = string.Empty; + string newDirName = "NewDirectory"; + + // Act + ErrorOr result = _sut.CreateDirectory(invalidPath, newDirName); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + } + + [Fact] + public void CreateDirectory_WithFileSystemPathId_ShouldReturnNewDirectory() + { + // Arrange + FileSystemPathId parentPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir"); + string newDirName = "NewDirectory"; + FileSystemPathId newDirPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(System.IO.Path.Combine(parentPathId.Path, newDirName)); + + _mockEnvironmentContext.DirectoryProviderService.CreateDirectory(parentPathId, newDirName) + .Returns(ErrorOrFactory.From(newDirPathId)); + _mockEnvironmentContext.DirectoryProviderService.GetFileName(newDirPathId) + .Returns(ErrorOrFactory.From(newDirName)); + _mockEnvironmentContext.DirectoryProviderService.GetLastWriteTime(newDirPathId) + .Returns(ErrorOrFactory.From(Optional.FromNullable(DateTime.Now))); + _mockEnvironmentContext.DirectoryProviderService.GetCreationTime(newDirPathId) + .Returns(ErrorOrFactory.From(Optional.FromNullable(DateTime.Now))); + + // Act + ErrorOr result = _sut.CreateDirectory(parentPathId, newDirName); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Id.Should().Be(newDirPathId); + } + + [Fact] + public void CreateDirectory_WhenDirectoryProviderServiceReturnsError_ShouldPropagateError() + { + // Arrange + FileSystemPathId parentPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir"); + string newDirName = "NewDirectory"; + + _mockEnvironmentContext.DirectoryProviderService.CreateDirectory(parentPathId, newDirName) + .Returns(Errors.Permission.UnauthorizedAccess); + + // Act + ErrorOr result = _sut.CreateDirectory(parentPathId, newDirName); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess); + } + + [Fact] + public void CreateDirectory_WhenDirectoryDetailsAreInaccessible_ShouldReturnInaccessibleDirectory() + { + // Arrange + FileSystemPathId parentPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir"); + string newDirName = "NewDirectory"; + FileSystemPathId newDirPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(System.IO.Path.Combine(parentPathId.Path, newDirName)); + + _mockEnvironmentContext.DirectoryProviderService.CreateDirectory(parentPathId, newDirName) + .Returns(ErrorOrFactory.From(newDirPathId)); + + _mockEnvironmentContext.DirectoryProviderService.GetFileName(newDirPathId) + .Returns(Errors.Permission.UnauthorizedAccess); + _mockEnvironmentContext.DirectoryProviderService.GetLastWriteTime(newDirPathId) + .Returns(Errors.Permission.UnauthorizedAccess); + _mockEnvironmentContext.DirectoryProviderService.GetCreationTime(newDirPathId) + .Returns(Errors.Permission.UnauthorizedAccess); + + // Act + ErrorOr result = _sut.CreateDirectory(parentPathId, newDirName); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Status.Should().Be(FileSystemItemStatus.Inaccessible); + result.Value.Id.Should().Be(newDirPathId); + result.Value.DateCreated.HasValue.Should().BeFalse(); + result.Value.DateModified.HasValue.Should().BeFalse(); + } + + [Fact] + public void CreateDirectory_WhenDirectoryExistsReturnsError_ShouldPropagateError() + { + // Arrange + FileSystemPathId parentPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir"); + string newDirName = "NewDirectory"; + FileSystemPathId newDirPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(System.IO.Path.Combine(parentPathId.Path, newDirName)); + + _mockPlatformContext.PathStrategy.CombinePath(parentPathId, newDirName).Returns(ErrorOrFactory.From(newDirPathId)); + _mockEnvironmentContext.DirectoryProviderService.DirectoryExists(newDirPathId) + .Returns(Errors.Permission.UnauthorizedAccess); + + // Act + ErrorOr result = _sut.CreateDirectory(parentPathId, newDirName); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess); + } + + [Fact] + public void CreateDirectory_WhenDirectoryAlreadyExists_ShouldReturnDirectoryAlreadyExistsError() + { + // Arrange + FileSystemPathId parentPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir"); + string newDirName = "ExistingDirectory"; + FileSystemPathId newDirPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(System.IO.Path.Combine(parentPathId.Path, newDirName)); + _mockPlatformContext.PathStrategy.CombinePath(parentPathId, newDirName).Returns(ErrorOrFactory.From(newDirPathId)); + + _mockEnvironmentContext.DirectoryProviderService.DirectoryExists(newDirPathId).Returns(true); + + // Act + ErrorOr result = _sut.CreateDirectory(parentPathId, newDirName); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.DirectoryAlreadyExists); + } + + [Fact] + public void CreateDirectory_WhenCombinePathReturnsError_ShouldReturnError() + { + // Arrange + FileSystemPathId parentPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir"); + string newDirName = "NewDirectory"; + + _mockPlatformContext.PathStrategy.CombinePath(parentPathId, newDirName) + .Returns(Errors.FileManagement.InvalidPath); + + // Act + ErrorOr result = _sut.CreateDirectory(parentPathId, newDirName); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + + // Verify that DirectoryExists was not called + _mockEnvironmentContext.DirectoryProviderService.DidNotReceive().DirectoryExists(Arg.Any()); + _mockEnvironmentContext.DirectoryProviderService.DidNotReceive().CreateDirectory(Arg.Any(), Arg.Any()); + } + + [Fact] + public void RenameDirectory_WithValidStringPath_ShouldReturnRenamedDirectory() + { + // Arrange + string oldPath = @"C:\TestDir\OldName"; + string newName = "NewName"; + FileSystemPathId oldPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(oldPath); + FileSystemPathId newPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir\NewName"); + + _mockEnvironmentContext.DirectoryProviderService.RenameDirectory(oldPathId, newName) + .Returns(ErrorOrFactory.From(newPathId)); + _mockEnvironmentContext.DirectoryProviderService.GetFileName(newPathId) + .Returns(ErrorOrFactory.From(newName)); + _mockEnvironmentContext.DirectoryProviderService.GetLastWriteTime(newPathId) + .Returns(ErrorOrFactory.From(Optional.FromNullable(DateTime.Now))); + _mockEnvironmentContext.DirectoryProviderService.GetCreationTime(newPathId) + .Returns(ErrorOrFactory.From(Optional.FromNullable(DateTime.Now))); + + // Act + ErrorOr result = _sut.RenameDirectory(oldPath, newName); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Id.Should().Be(newPathId); + result.Value.Name.Should().Be(newName); + } + + [Fact] + public void RenameDirectory_WithInvalidStringPath_ShouldReturnError() + { + // Arrange + string invalidPath = string.Empty; + string newName = "NewName"; + + // Act + ErrorOr result = _sut.RenameDirectory(invalidPath, newName); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + } + + [Fact] + public void RenameDirectory_WithFileSystemPathId_ShouldReturnRenamedDirectory() + { + // Arrange + FileSystemPathId oldPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir\OldName"); + string newName = "NewName"; + FileSystemPathId newPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir\NewName"); + + _mockEnvironmentContext.DirectoryProviderService.RenameDirectory(oldPathId, newName) + .Returns(ErrorOrFactory.From(newPathId)); + _mockEnvironmentContext.DirectoryProviderService.GetFileName(newPathId) + .Returns(ErrorOrFactory.From(newName)); + _mockEnvironmentContext.DirectoryProviderService.GetLastWriteTime(newPathId) + .Returns(ErrorOrFactory.From(Optional.FromNullable(DateTime.Now))); + _mockEnvironmentContext.DirectoryProviderService.GetCreationTime(newPathId) + .Returns(ErrorOrFactory.From(Optional.FromNullable(DateTime.Now))); + + // Act + ErrorOr result = _sut.RenameDirectory(oldPathId, newName); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Id.Should().Be(newPathId); + result.Value.Name.Should().Be(newName); + } + + [Fact] + public void RenameDirectory_WhenDirectoryProviderServiceReturnsError_ShouldPropagateError() + { + // Arrange + FileSystemPathId oldPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir\OldName"); + string newName = "NewName"; + + _mockEnvironmentContext.DirectoryProviderService.RenameDirectory(oldPathId, newName) + .Returns(Errors.Permission.UnauthorizedAccess); + + // Act + ErrorOr result = _sut.RenameDirectory(oldPathId, newName); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess); + } + + [Fact] + public void RenameDirectory_WhenDirectoryDetailsAreInaccessible_ShouldReturnInaccessibleDirectory() + { + // Arrange + FileSystemPathId oldPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir\OldName"); + string newName = "NewName"; + FileSystemPathId newPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir\NewName"); + + _mockEnvironmentContext.DirectoryProviderService.RenameDirectory(oldPathId, newName) + .Returns(ErrorOrFactory.From(newPathId)); + + _mockEnvironmentContext.DirectoryProviderService.GetFileName(newPathId) + .Returns(Errors.Permission.UnauthorizedAccess); + _mockEnvironmentContext.DirectoryProviderService.GetLastWriteTime(newPathId) + .Returns(Errors.Permission.UnauthorizedAccess); + _mockEnvironmentContext.DirectoryProviderService.GetCreationTime(newPathId) + .Returns(Errors.Permission.UnauthorizedAccess); + + // Act + ErrorOr result = _sut.RenameDirectory(oldPathId, newName); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Status.Should().Be(FileSystemItemStatus.Inaccessible); + result.Value.Id.Should().Be(newPathId); + result.Value.DateCreated.HasValue.Should().BeFalse(); + result.Value.DateModified.HasValue.Should().BeFalse(); + } + + [Fact] + public void RenameDirectory_WhenDirectoryAlreadyExists_ShouldReturnDirectoryAlreadyExistsError() + { + // Arrange + FileSystemPathId oldPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir\OldName"); + string newName = "ExistingDirectory"; + FileSystemPathId newPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir\ExistingDirectory"); + + _mockPlatformContext.PathStrategy.CombinePath(Arg.Any(), newName) + .Returns(ErrorOrFactory.From(newPathId)); + _mockEnvironmentContext.DirectoryProviderService.DirectoryExists(newPathId) + .Returns(ErrorOrFactory.From(true)); + + // Act + ErrorOr result = _sut.RenameDirectory(oldPathId, newName); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.DirectoryAlreadyExists); + } + + [Fact] + public void RenameDirectory_WhenCombinePathReturnsError_ShouldReturnError() + { + // Arrange + FileSystemPathId oldPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir\OldName"); + string newName = "NewName"; + + _mockPlatformContext.PathStrategy.CombinePath(Arg.Any(), newName) + .Returns(Errors.FileManagement.InvalidPath); + + // Act + ErrorOr result = _sut.RenameDirectory(oldPathId, newName); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + + // Verify that DirectoryExists and RenameDirectory were not called + _mockEnvironmentContext.DirectoryProviderService.DidNotReceive().DirectoryExists(Arg.Any()); + _mockEnvironmentContext.DirectoryProviderService.DidNotReceive().RenameDirectory(Arg.Any(), Arg.Any()); + } + + [Fact] + public void RenameDirectory_WhenDirectoryExistsReturnsError_ShouldPropagateError() + { + // Arrange + FileSystemPathId oldPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir\OldName"); + string newName = "NewName"; + FileSystemPathId newPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir\NewName"); + + _mockPlatformContext.PathStrategy.CombinePath(Arg.Any(), newName) + .Returns(ErrorOrFactory.From(newPathId)); + + _mockEnvironmentContext.DirectoryProviderService.DirectoryExists(newPathId) + .Returns(Errors.Permission.UnauthorizedAccess); + + // Act + ErrorOr result = _sut.RenameDirectory(oldPathId, newName); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess); + + // Verify that RenameDirectory was not called + _mockEnvironmentContext.DirectoryProviderService.DidNotReceive().RenameDirectory(Arg.Any(), Arg.Any()); + } + + [Fact] + public void DeleteDirectory_WithValidStringPath_ShouldReturnDeleted() + { + // Arrange + string path = @"C:\TestDir\ToDelete"; + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); + + _mockEnvironmentContext.DirectoryProviderService.DeleteDirectory(pathId) + .Returns(Result.Deleted); + + // Act + ErrorOr result = _sut.DeleteDirectory(path); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().Be(Result.Deleted); + } + + [Fact] + public void DeleteDirectory_WithInvalidStringPath_ShouldReturnError() + { + // Arrange + string invalidPath = string.Empty; + + // Act + ErrorOr result = _sut.DeleteDirectory(invalidPath); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + } + + [Fact] + public void DeleteDirectory_WithFileSystemPathId_ShouldReturnDeleted() + { + // Arrange + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir\ToDelete"); + + _mockEnvironmentContext.DirectoryProviderService.DeleteDirectory(pathId) + .Returns(Result.Deleted); + + // Act + ErrorOr result = _sut.DeleteDirectory(pathId); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().Be(Result.Deleted); + } + + [Fact] + public void DeleteDirectory_WhenDirectoryProviderServiceReturnsError_ShouldPropagateError() + { + // Arrange + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir\ToDelete"); + + _mockEnvironmentContext.DirectoryProviderService.DeleteDirectory(pathId) + .Returns(Errors.Permission.UnauthorizedAccess); + + // Act + ErrorOr result = _sut.DeleteDirectory(pathId); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess); + } + + [Fact] + public void DeleteDirectory_WhenDirectoryDoesNotExist_ShouldReturnDirectoryNotFoundError() + { + // Arrange + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir\NonExistent"); + + _mockEnvironmentContext.DirectoryProviderService.DeleteDirectory(pathId) + .Returns(Errors.FileManagement.DirectoryNotFound); + + // Act + ErrorOr result = _sut.DeleteDirectory(pathId); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.DirectoryNotFound); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Services/DriveServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Services/DriveServiceTests.cs new file mode 100644 index 00000000..8067d15c --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Services/DriveServiceTests.cs @@ -0,0 +1,94 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FluentAssertions; +using Lumina.Contracts.Enums.FileSystem; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; +using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Fixtures; +using NSubstitute; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO.Abstractions; +using System.Linq; +#endregion + +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Services; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DriveServiceTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly IFileSystem _mockFileSystem; + private readonly IPlatformContextManager _mockPlatformContextManager; + private readonly IPlatformContext _mockPlatformContext; + private readonly DriveService _sut; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public DriveServiceTests() + { + _mockFileSystem = Substitute.For(); + _mockPlatformContextManager = Substitute.For(); + _mockPlatformContext = Substitute.For(); + _mockPlatformContextManager.GetCurrentContext().Returns(_mockPlatformContext); + _sut = new DriveService(_mockFileSystem, _mockPlatformContextManager); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public void GetDrives_OnUnixPlatform_ShouldReturnSingleUnixRootItem() + { + // Arrange + _mockPlatformContext.Platform.Returns(PlatformType.Unix); + + // Act + ErrorOr> result = _sut.GetDrives(); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().HaveCount(1); + result.Value.First().Should().BeOfType(); + result.Value.First().Status.Should().Be(FileSystemItemStatus.Accessible); + } + + [Fact] + public void GetDrives_OnWindowsPlatform_ShouldReturnWindowsRootItems() + { + // Arrange + _mockPlatformContext.Platform.Returns(PlatformType.Windows); + IDriveInfo[] mockDrives = + [ + CreateMockDriveInfo("C:\\", true), + CreateMockDriveInfo("D:\\", true), + CreateMockDriveInfo("E:\\", false) // Not ready + ]; + _mockFileSystem.DriveInfo.GetDrives().Returns(mockDrives); + + // Act + ErrorOr> result = _sut.GetDrives(); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().HaveCount(2); // Only ready drives + result.Value.Should().AllBeOfType(); + result.Value.Select(d => d.Name).Should().BeEquivalentTo("C:\\", "D:\\"); + } + + private static IDriveInfo CreateMockDriveInfo(string name, bool isReady) + { + IDriveInfo mockDriveInfo = Substitute.For(); + mockDriveInfo.Name.Returns(name); + mockDriveInfo.IsReady.Returns(isReady); + return mockDriveInfo; + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Services/FileProviderServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Services/FileProviderServiceTests.cs new file mode 100644 index 00000000..3e93e282 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Services/FileProviderServiceTests.cs @@ -0,0 +1,899 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using AutoFixture.AutoNSubstitute; +using ErrorOr; +using FluentAssertions; +using Lumina.Contracts.Enums.FileSystem; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects.Fixtures; +using NSubstitute; +using NSubstitute.ExceptionExtensions; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.IO.Abstractions; +using System.Linq; +#endregion + +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Services; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class FileProviderServiceTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly IFixture _fixture; + private readonly IFileSystem _mockFileSystem; + private readonly IFileSystemPermissionsService _mockFileSystemPermissionsService; + private readonly FileProviderService _sut; + private readonly FileSystemPathIdFixture _fileSystemPathIdFixture; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public FileProviderServiceTests() + { + _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); + _mockFileSystem = Substitute.For(); + _mockFileSystemPermissionsService = Substitute.For(); + _sut = new FileProviderService(_mockFileSystem, _mockFileSystemPermissionsService); + _fileSystemPathIdFixture = new(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public void GetFilePaths_WhenUserHasNoAccess_ShouldReturnUnauthorizedAccessError() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); + _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory).Returns(false); + + // Act + ErrorOr> result = _sut.GetFilePaths(path, false); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess); + } + + [Fact] + public void GetFilePaths_WhenUserHasAccess_ShouldReturnFiles() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); + string[] files = _fixture.CreateMany(3).ToArray(); + _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory).Returns(true); + _mockFileSystem.Directory.GetFiles(path.Path).Returns(files); + + // Act + ErrorOr> result = _sut.GetFilePaths(path, false); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().HaveCount(3); + result.Value.Select(x => x.Path).Should().BeEquivalentTo(files); + } + + [Fact] + public void GetFilePaths_WhenIncludeHiddenElementsIsFalse_ShouldExcludeHiddenFiles() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); + string[] files = [@"C:\Visible.txt", @"C:\Hidden.txt"]; + _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory).Returns(true); + _mockFileSystem.Directory.GetFiles(path.Path).Returns(files); + _mockFileSystem.File.GetAttributes(@"C:\Visible.txt").Returns(FileAttributes.Normal); + _mockFileSystem.File.GetAttributes(@"C:\Hidden.txt").Returns(FileAttributes.Hidden); + + // Act + ErrorOr> result = _sut.GetFilePaths(path, false); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().HaveCount(1); + result.Value.First().Path.Should().Be(@"C:\Visible.txt"); + } + + [Fact] + public void GetFilePaths_WhenIncludeHiddenElementsIsTrue_ShouldIncludeHiddenFiles() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); + string[] files = [@"C:\Visible.txt", @"C:\Hidden.txt"]; + _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory).Returns(true); + _mockFileSystem.Directory.GetFiles(path.Path).Returns(files); + _mockFileSystem.File.GetAttributes(@"C:\Visible.txt").Returns(FileAttributes.Normal); + _mockFileSystem.File.GetAttributes(@"C:\Hidden.txt").Returns(FileAttributes.Hidden); + + // Act + ErrorOr> result = _sut.GetFilePaths(path, true); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().HaveCount(2); + result.Value.Select(x => x.Path).Should().BeEquivalentTo([@"C:\Visible.txt", @"C:\Hidden.txt"]); + } + + [Fact] + public void GetFilePaths_WhenGetAttributesThrowsException_ShouldStillAddFile() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); + string[] files = [@"C:\Valid.txt", @"C:\Invalid.txt"]; + _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory).Returns(true); + _mockFileSystem.Directory.GetFiles(path.Path).Returns(files); + _mockFileSystem.File.GetAttributes(@"C:\Valid.txt").Returns(FileAttributes.Normal); + _mockFileSystem.File.GetAttributes(@"C:\Invalid.txt").Throws(new Exception("Access denied")); + + // Act + ErrorOr> result = _sut.GetFilePaths(path, false); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().HaveCount(2); + result.Value.Select(x => x.Path).Should().BeEquivalentTo([@"C:\Invalid.txt", @"C:\Valid.txt"]); + } + + [Fact] + public void GetFilePaths_ShouldOrderFilesAlphabetically() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); + string[] files = [@"C:\C.txt", @"C:\A.txt", @"C:\B.txt"]; + _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory).Returns(true); + _mockFileSystem.Directory.GetFiles(path.Path).Returns(files); + _mockFileSystem.File.GetAttributes(Arg.Any()).Returns(FileAttributes.Normal); + + // Act + ErrorOr> result = _sut.GetFilePaths(path, false); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Select(x => x.Path).Should().BeEquivalentTo([@"C:\A.txt", @"C:\B.txt", @"C:\C.txt"], options => options.WithStrictOrdering()); + } + + [Fact] + public void GetFilePaths_WhenDirectoryHasNoFiles_ShouldReturnEmptyList() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); + _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory).Returns(true); + _mockFileSystem.Directory.GetFiles(path.Path).Returns([]); + + // Act + ErrorOr> result = _sut.GetFilePaths(path, false); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().BeEmpty(); + } + + [Fact] + public void FileExists_WhenFileExists_ShouldReturnTrue() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); + _mockFileSystem.File.Exists(path.Path).Returns(true); + + // Act + ErrorOr result = _sut.FileExists(path); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().BeTrue(); + } + + [Fact] + public void FileExists_WhenFileDoesNotExist_ShouldReturnFalse() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); + _mockFileSystem.File.Exists(path.Path).Returns(false); + + // Act + ErrorOr result = _sut.FileExists(path); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().BeFalse(); + } + + [Fact] + public void GetFileName_WhenPathIsValid_ShouldReturnFileName() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); + string expectedFileName = "testfile.txt"; + _mockFileSystem.Path.GetFileName(path.Path).Returns(expectedFileName); + + // Act + ErrorOr result = _sut.GetFileName(path); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().Be(expectedFileName); + } + + [Fact] + public void GetFileName_WhenPathIsEmpty_ShouldReturnEmptyString() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); + _mockFileSystem.Path.GetFileName(path.Path).Returns(string.Empty); + + // Act + ErrorOr result = _sut.GetFileName(path); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().BeEmpty(); + } + + [Fact] + public void GetFileAsync_WhenUserHasAccess_ShouldReturnFileContents() + { + // Arrange + string tempFilePath = Path.GetTempFileName(); + try + { + byte[] expectedContents = [1, 2, 3, 4, 5]; + File.WriteAllBytes(tempFilePath, expectedContents); + + FileSystemPathId path = FileSystemPathId.Create(tempFilePath).Value; + _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadContents).Returns(true); + + // We need to update the _fileSystem mock to use the real file system for this method + _mockFileSystem.File.ReadAllBytes(tempFilePath).Returns(x => File.ReadAllBytes(x.Arg())); + + // Act + ErrorOr result = _sut.GetFileAsync(path); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().BeEquivalentTo(expectedContents); + } + finally + { + // Clean up + File.Delete(tempFilePath); + } + } + + [Fact] + public void GetFileAsync_WhenUserHasNoAccess_ShouldReturnUnauthorizedAccessError() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); + _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadContents).Returns(false); + + // Act + ErrorOr result = _sut.GetFileAsync(path); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess); + } + + [Fact] + public void GetFileAsync_WhenFileIsEmpty_ShouldReturnEmptyByteArray() + { + // Arrange + string tempFilePath = Path.GetTempFileName(); + try + { + FileSystemPathId path = FileSystemPathId.Create(tempFilePath).Value; + _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadContents).Returns(true); + + // Act + ErrorOr result = _sut.GetFileAsync(path); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().BeEmpty(); + } + finally + { + // Clean up + File.Delete(tempFilePath); + } + } + + [Fact] + public void GetLastWriteTime_WhenUserHasAccess_ShouldReturnLastWriteTime() + { + // Arrange + string tempFilePath = Path.GetTempFileName(); + try + { + File.WriteAllText(tempFilePath, "Test content"); + FileSystemPathId path = FileSystemPathId.Create(tempFilePath).Value; + DateTime expectedDateTime = File.GetLastWriteTime(tempFilePath); + + _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties).Returns(true); + _mockFileSystem.File.GetLastWriteTime(path.Path).Returns(expectedDateTime); + + // Act + ErrorOr> result = _sut.GetLastWriteTime(path); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.HasValue.Should().BeTrue(); + result.Value.Value.Should().BeCloseTo(expectedDateTime, TimeSpan.FromSeconds(1)); + } + finally + { + File.Delete(tempFilePath); + } + } + + [Fact] + public void GetLastWriteTime_WhenUserHasNoAccess_ShouldReturnUnauthorizedAccessError() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); + _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties).Returns(false); + + // Act + ErrorOr> result = _sut.GetLastWriteTime(path); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess); + } + + [Fact] + public void GetCreationTime_WhenUserHasAccess_ShouldReturnCreationTime() + { + // Arrange + string tempFilePath = Path.GetTempFileName(); + try + { + File.WriteAllText(tempFilePath, "Test content"); + FileSystemPathId path = FileSystemPathId.Create(tempFilePath).Value; + DateTime expectedDateTime = File.GetCreationTime(tempFilePath); + + _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties).Returns(true); + _mockFileSystem.File.GetCreationTime(path.Path).Returns(expectedDateTime); + + // Act + ErrorOr> result = _sut.GetCreationTime(path); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.HasValue.Should().BeTrue(); + result.Value.Value.Should().BeCloseTo(expectedDateTime, TimeSpan.FromSeconds(1)); + } + finally + { + File.Delete(tempFilePath); + } + } + + [Fact] + public void GetCreationTime_WhenUserHasNoAccess_ShouldReturnUnauthorizedAccessError() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); + _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties).Returns(false); + + // Act + ErrorOr> result = _sut.GetCreationTime(path); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess); + } + + [Fact] + public void GetSize_WhenUserHasAccess_ShouldReturnFileSize() + { + // Arrange + string tempFilePath = Path.GetTempFileName(); + try + { + string content = "Test content"; + File.WriteAllText(tempFilePath, content); + FileSystemPathId path = FileSystemPathId.Create(tempFilePath).Value; + long expectedSize = new FileInfo(tempFilePath).Length; + + _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties).Returns(true); + _mockFileSystem.FileInfo.New(path.Path).Returns(new FileInfoWrapper(_mockFileSystem, new FileInfo(tempFilePath))); + + // Act + ErrorOr result = _sut.GetSize(path); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Should().Be(expectedSize); + } + finally + { + File.Delete(tempFilePath); + } + } + + [Fact] + public void GetSize_WhenUserHasNoAccess_ShouldReturnUnauthorizedAccessError() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(); + _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties).Returns(false); + + // Act + ErrorOr result = _sut.GetSize(path); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess); + } + + [Fact] + public void GetSize_WhenFileDoesNotExist_ShouldReturnZero() + { + // Arrange + string nonExistentFilePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + FileSystemPathId path = FileSystemPathId.Create(nonExistentFilePath).Value; + + _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties).Returns(true); + _mockFileSystem.FileInfo.New(path.Path).Returns((IFileInfo)null!); + + // Act + ErrorOr result = _sut.GetSize(path); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().Be(0); + } + + [Fact] + public void CopyFile_WhenSourceFileExistsAndUserHasAccess_ShouldCopyFileAndReturnPath() + { + // Arrange + FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Source\file.txt"); + FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Destination"); + bool overrideExisting = false; + + _mockFileSystem.File.Exists(sourcePath.Path).Returns(true); + _mockFileSystem.File.Exists(Path.Combine(destinationPath.Path, "file.txt")).Returns(false); + + _mockFileSystem.Path.GetFileName(sourcePath.Path).Returns("file.txt"); + _mockFileSystem.Path.Combine(destinationPath.Path, "file.txt").Returns(@"C:\Destination\file.txt"); + + // Act + ErrorOr result = _sut.CopyFile(sourcePath, destinationPath, overrideExisting); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Path.Should().Be(@"C:\Destination\file.txt"); + _mockFileSystem.File.Received(1).Copy(sourcePath.Path, @"C:\Destination\file.txt", overrideExisting); + } + + [Fact] + public void CopyFile_WhenSourceFileDoesNotExist_ShouldReturnError() + { + // Arrange + FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId(); + FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(); + bool overrideExisting = false; + + _mockFileSystem.File.Exists(sourcePath.Path).Returns(false); + + // Act + ErrorOr result = _sut.CopyFile(sourcePath, destinationPath, overrideExisting); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.FileNotFound); + } + + [Fact] + public void CopyFile_WhenDestinationFileExistsAndOverrideIsFalse_ShouldReturnFileAlreadyExistsError() + { + // Arrange + FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Source\file.txt"); + FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Destination"); + string expectedDestinationFilePath = @"C:\Destination\file.txt"; + bool overrideExisting = false; + + _mockFileSystem.File.Exists(sourcePath.Path).Returns(true); + _mockFileSystem.File.Exists(expectedDestinationFilePath).Returns(true); + + _mockFileSystem.Path.GetFileName(sourcePath.Path).Returns("file.txt"); + _mockFileSystem.Path.GetDirectoryName(sourcePath.Path).Returns(@"C:\Source"); + + _mockFileSystem.Path.Combine(Arg.Any(), Arg.Any()) + .Returns(callInfo => Path.Combine(callInfo.ArgAt(0), callInfo.ArgAt(1))); + + // Act + ErrorOr result = _sut.CopyFile(sourcePath, destinationPath, overrideExisting); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.FileAlreadyExists); + _mockFileSystem.File.DidNotReceive().Copy(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public void CopyFile_WhenOverrideExistingIsTrue_ShouldOverwriteExistingFile() + { + // Arrange + FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Source\file.txt"); + FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Destination"); + bool overrideExisting = true; + + _mockFileSystem.File.Exists(sourcePath.Path).Returns(true); + _mockFileSystem.File.Exists(@"C:\Destination\file.txt").Returns(true); + + _mockFileSystem.Path.GetFileName(sourcePath.Path).Returns("file.txt"); + _mockFileSystem.Path.Combine(destinationPath.Path, "file.txt").Returns(@"C:\Destination\file.txt"); + + // Act + ErrorOr result = _sut.CopyFile(sourcePath, destinationPath, overrideExisting); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Path.Should().Be(@"C:\Destination\file.txt"); + _mockFileSystem.File.Received(1).Copy(sourcePath.Path, @"C:\Destination\file.txt", overrideExisting); + } + + [Fact] + public void CopyFile_WhenExceptionOccurs_ShouldReturnError() + { + // Arrange + FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId(); + FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(); + bool overrideExisting = false; + + _mockFileSystem.File.Exists(sourcePath.Path).Returns(true); + _mockFileSystem.File.When(x => x.Copy(Arg.Any(), Arg.Any(), Arg.Any())) + .Do(x => { throw new Exception("Simulated error"); }); + + // Act + ErrorOr result = _sut.CopyFile(sourcePath, destinationPath, overrideExisting); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.FileCopyError); + } + + [Fact] + public void CopyFile_WhenCopyingToSameDirectory_ShouldCreateUniqueFileName() + { + // Arrange + string sourceDirectory = @"C:\Source"; + FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId(Path.Combine(sourceDirectory, "file.txt")); + FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(sourceDirectory); + string expectedNewFilePath = Path.Combine(sourceDirectory, "file - Copy (1).txt"); + bool overrideExisting = false; + + _mockFileSystem.File.Exists(sourcePath.Path).Returns(true); + _mockFileSystem.File.Exists(Path.Combine(sourceDirectory, "file.txt")).Returns(true); + _mockFileSystem.File.Exists(expectedNewFilePath).Returns(false); + + _mockFileSystem.Path.GetFileName(sourcePath.Path).Returns("file.txt"); + _mockFileSystem.Path.GetDirectoryName(sourcePath.Path).Returns(sourceDirectory); + _mockFileSystem.Path.GetFileNameWithoutExtension(Arg.Any()).Returns(x => Path.GetFileNameWithoutExtension(x.Arg())); + _mockFileSystem.Path.GetExtension(Arg.Any()).Returns(x => Path.GetExtension(x.Arg())); + + _mockFileSystem.Path.Combine(Arg.Any(), Arg.Any()) + .Returns(callInfo => Path.Combine(callInfo.ArgAt(0), callInfo.ArgAt(1))); + + // Simulate the behavior of CreateUniqueFilePath + int copyNumber = 1; + _mockFileSystem.File.Exists(Arg.Any()) + .Returns(x => { + string path = x.Arg(); + if (path == expectedNewFilePath) + return false; + copyNumber++; + return true; + }); + + // Act + ErrorOr result = _sut.CopyFile(sourcePath, destinationPath, overrideExisting); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Path.Should().Be(expectedNewFilePath); + _mockFileSystem.File.Received(1).Copy(sourcePath.Path, expectedNewFilePath, overrideExisting); + } + + [Fact] + public void MoveFile_WhenSourceFileDoesNotExist_ShouldReturnFileNotFoundError() + { + // Arrange + FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\NonExistentSource.txt"); + FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Destination"); + bool overrideExisting = false; + + _mockFileSystem.File.Exists(sourcePath.Path).Returns(false); + + // Act + ErrorOr result = _sut.MoveFile(sourcePath, destinationPath, overrideExisting); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.FileNotFound); + } + + [Fact] + public void MoveFile_WhenDestinationFileDoesNotExist_ShouldPerformSimpleMove() + { + // Arrange + FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Source\file.txt"); + FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Destination"); + string destinationFilePath = @"C:\Destination\file.txt"; + bool overrideExisting = false; + + _mockFileSystem.File.Exists(sourcePath.Path).Returns(true); + _mockFileSystem.File.Exists(destinationFilePath).Returns(false); + _mockFileSystem.Path.GetFileName(sourcePath.Path).Returns("file.txt"); + _mockFileSystem.Path.Combine(destinationPath.Path, "file.txt").Returns(destinationFilePath); + + // Act + ErrorOr result = _sut.MoveFile(sourcePath, destinationPath, overrideExisting); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Path.Should().Be(destinationFilePath); + _mockFileSystem.File.Received(1).Move(sourcePath.Path, destinationFilePath); + } + + [Fact] + public void MoveFile_WhenDestinationFileExistsAndOverrideIsTrue_ShouldOverwriteFile() + { + // Arrange + FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Source\file.txt"); + FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Destination"); + string destinationFilePath = @"C:\Destination\file.txt"; + bool overrideExisting = true; + + _mockFileSystem.File.Exists(sourcePath.Path).Returns(true); + _mockFileSystem.File.Exists(destinationFilePath).Returns(true); + _mockFileSystem.Path.GetFileName(sourcePath.Path).Returns("file.txt"); + _mockFileSystem.Path.Combine(destinationPath.Path, "file.txt").Returns(destinationFilePath); + + // Act + ErrorOr result = _sut.MoveFile(sourcePath, destinationPath, overrideExisting); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Path.Should().Be(destinationFilePath); + _mockFileSystem.File.Received(1).Move(sourcePath.Path, destinationFilePath, overrideExisting); + } + + [Fact] + public void MoveFile_WhenDestinationFileExistsAndOverrideIsFalse_ShouldReturnFileAlreadyExistsError() + { + // Arrange + FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Source\file.txt"); + FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Destination"); + string destinationFilePath = @"C:\Destination\file.txt"; + bool overrideExisting = false; + + _mockFileSystem.File.Exists(sourcePath.Path).Returns(true); + _mockFileSystem.File.Exists(destinationFilePath).Returns(true); + _mockFileSystem.Path.GetFileName(sourcePath.Path).Returns("file.txt"); + _mockFileSystem.Path.Combine(destinationPath.Path, "file.txt").Returns(destinationFilePath); + + // Act + ErrorOr result = _sut.MoveFile(sourcePath, destinationPath, overrideExisting); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.FileAlreadyExists); + } + + [Fact] + public void MoveFile_WhenExceptionOccurs_ShouldReturnFileMoveError() + { + // Arrange + FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Source\file.txt"); + FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Destination"); + string destinationFilePath = @"C:\Destination\file.txt"; + bool overrideExisting = false; + + _mockFileSystem.File.Exists(sourcePath.Path).Returns(true); + _mockFileSystem.File.Exists(destinationFilePath).Returns(false); + _mockFileSystem.Path.GetFileName(sourcePath.Path).Returns("file.txt"); + _mockFileSystem.Path.Combine(destinationPath.Path, "file.txt").Returns(destinationFilePath); + _mockFileSystem.File.When(x => x.Move(Arg.Any(), Arg.Any())) + .Do(x => throw new IOException("Simulated IO error")); + + // Act + ErrorOr result = _sut.MoveFile(sourcePath, destinationPath, overrideExisting); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.FileMoveError); + } + + [Fact] + public void RenameFile_WhenParentDirectoryIsWritable_ShouldRenameSuccessfully() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\OldName.txt"); + string newName = "NewName.txt"; + string parentPath = @"C:\"; + string newPath = @"C:\NewName.txt"; + + IFileInfo fileInfo = Substitute.For(); + fileInfo.DirectoryName.Returns(parentPath); + _mockFileSystem.FileInfo.New(path.Path).Returns(fileInfo); + _mockFileSystem.Path.Combine(parentPath, newName).Returns(newPath); + _mockFileSystemPermissionsService.CanAccessPath(Arg.Any(), FileAccessMode.Write).Returns(true); + _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Execute).Returns(true); + + // Act + ErrorOr result = _sut.RenameFile(path, newName); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Path.Should().Be(newPath); + _mockFileSystem.File.Received(1).Move(path.Path, newPath); + } + + [Fact] + public void RenameFile_WhenParentDirectoryIsNotWritable_ShouldReturnUnauthorizedAccessError() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\OldName.txt"); + string newName = "NewName.txt"; + string parentPath = @"C:\"; + string newPath = @"C:\NewName.txt"; + + IFileInfo fileInfo = Substitute.For(); + fileInfo.DirectoryName.Returns(parentPath); + _mockFileSystem.FileInfo.New(path.Path).Returns(fileInfo); + _mockFileSystem.Path.Combine(parentPath, newName).Returns(newPath); + _mockFileSystemPermissionsService.CanAccessPath(Arg.Any(), FileAccessMode.Write).Returns(false); + + // Act + ErrorOr result = _sut.RenameFile(path, newName); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess); + _mockFileSystem.File.DidNotReceive().Move(Arg.Any(), Arg.Any()); + } + + [Fact] + public void RenameFile_WhenFileIsNotExecutable_ShouldReturnUnauthorizedAccessError() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\OldName.txt"); + string newName = "NewName.txt"; + string parentPath = @"C:\"; + string newPath = @"C:\NewName.txt"; + + IFileInfo fileInfo = Substitute.For(); + fileInfo.DirectoryName.Returns(parentPath); + _mockFileSystem.FileInfo.New(path.Path).Returns(fileInfo); + _mockFileSystem.Path.Combine(parentPath, newName).Returns(newPath); + _mockFileSystemPermissionsService.CanAccessPath(Arg.Any(), FileAccessMode.Write).Returns(true); + _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Execute).Returns(false); + + // Act + ErrorOr result = _sut.RenameFile(path, newName); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess); + _mockFileSystem.File.DidNotReceive().Move(Arg.Any(), Arg.Any()); + } + + [Fact] + public void RenameFile_WhenParentDirectoryIsNull_ShouldReturnInvalidPathError() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\OldName.txt"); + string newName = "NewName.txt"; + + _mockFileSystem.FileInfo.New(path.Path).Returns((IFileInfo)null!); + + // Act + ErrorOr result = _sut.RenameFile(path, newName); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.CannotNavigateUp); + _mockFileSystem.File.DidNotReceive().Move(Arg.Any(), Arg.Any()); + } + + [Fact] + public void RenameFile_WhenNewPathIsInvalid_ShouldReturnInvalidPathError() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\OldName.txt"); + string newName = "NewName.txt"; + string parentPath = @"C:\"; + + IFileInfo fileInfo = Substitute.For(); + fileInfo.DirectoryName.Returns(parentPath); + _mockFileSystem.FileInfo.New(path.Path).Returns(fileInfo); + _mockFileSystem.Path.Combine(parentPath, newName).Returns((string)null!); + + // Act + ErrorOr result = _sut.RenameFile(path, newName); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + _mockFileSystem.File.DidNotReceive().Move(Arg.Any(), Arg.Any()); + } + + [Fact] + public void RenameFile_WhenParentDirectoryExistsButNotWritable_ShouldReturnUnauthorizedAccessError() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\OldName.txt"); + string newName = "NewName.txt"; + string parentPath = @"C:\"; + string newPath = @"C:\NewName.txt"; + + IFileInfo fileInfo = Substitute.For(); + fileInfo.DirectoryName.Returns(parentPath); + _mockFileSystem.FileInfo.New(path.Path).Returns(fileInfo); + _mockFileSystem.Path.Combine(parentPath, newName).Returns(newPath); + + // Mock successful creation of parent directory FileSystemPathId + ErrorOr parentDirectoryPathId = FileSystemPathId.Create(parentPath); + _mockFileSystem.Path.GetDirectoryName(path.Path).Returns(parentPath); + + // Mock permissions: executable for the file, but not writable for the parent directory + _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Execute).Returns(true); + _mockFileSystemPermissionsService.CanAccessPath(Arg.Is(x => x.Path == parentPath), FileAccessMode.Write).Returns(false); + + // Act + ErrorOr result = _sut.RenameFile(path, newName); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess); + _mockFileSystem.File.DidNotReceive().Move(Arg.Any(), Arg.Any()); + } + + [Fact] + public void DeleteFile_WhenFileExistsAndHasDeletePermission_ShouldDeleteSuccessfully() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\FileToDelete.txt"); + _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Delete).Returns(true); + _mockFileSystem.File.Exists(path.Path).Returns(true); + + // Act + ErrorOr result = _sut.DeleteFile(path); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().Be(Result.Deleted); + _mockFileSystem.File.Received(1).Delete(path.Path); + } + + [Fact] + public void DeleteFile_WhenNoDeletePermission_ShouldReturnUnauthorizedAccessError() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\FileToDelete.txt"); + _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Delete).Returns(false); + + // Act + ErrorOr result = _sut.DeleteFile(path); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess); + _mockFileSystem.File.DidNotReceive().Delete(Arg.Any()); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Services/FileServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Services/FileServiceTests.cs new file mode 100644 index 00000000..652ffef6 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Services/FileServiceTests.cs @@ -0,0 +1,1203 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FluentAssertions; +using Lumina.Contracts.Enums.FileSystem; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Environment; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Entities.Fixtures; +using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects.Fixtures; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Services; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class FileServiceTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly IEnvironmentContext _mockEnvironmentContext; + private readonly IPlatformContextManager _mockPlatformContextManager; + private readonly IPlatformContext _mockPlatformContext; + private readonly FileService _sut; + private readonly FileSystemPathIdFixture _fileSystemPathIdFixture; + private readonly FileFixture _fileFixture; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public FileServiceTests() + { + _mockEnvironmentContext = Substitute.For(); + _mockPlatformContextManager = Substitute.For(); + _mockPlatformContext = Substitute.For(); + _mockPlatformContextManager.GetCurrentContext().Returns(_mockPlatformContext); + _sut = new FileService(_mockEnvironmentContext, _mockPlatformContextManager); + _fileSystemPathIdFixture = new FileSystemPathIdFixture(); + _fileFixture = new FileFixture(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public void GetFiles_WithValidPath_ShouldReturnListOfFiles() + { + // Arrange + string path = @"C:\TestDir"; + bool includeHiddenElements = false; + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); + FileSystemPathId[] filePaths = + [ + _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir\File1.txt"), + _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir\File2.txt") + ]; + + _mockEnvironmentContext.FileProviderService.GetFilePaths(pathId, includeHiddenElements) + .Returns(ErrorOrFactory.From(filePaths.AsEnumerable())); + + foreach (FileSystemPathId filePath in filePaths) + { + _mockEnvironmentContext.FileProviderService.GetFileName(filePath) + .Returns(ErrorOrFactory.From(System.IO.Path.GetFileName(filePath.Path))); + _mockEnvironmentContext.FileProviderService.GetLastWriteTime(filePath) + .Returns(ErrorOrFactory.From(Optional.FromNullable(DateTime.Now))); + _mockEnvironmentContext.FileProviderService.GetCreationTime(filePath) + .Returns(ErrorOrFactory.From(Optional.FromNullable(DateTime.Now.AddDays(-1)))); + _mockEnvironmentContext.FileProviderService.GetSize(filePath) + .Returns(ErrorOrFactory.From((long?)1024)); + } + + // Act + ErrorOr> result = _sut.GetFiles(path, includeHiddenElements); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().HaveCount(2); + result.Value.Select(f => f.Name).Should().BeEquivalentTo(["File1.txt", "File2.txt"]); + } + + [Fact] + public void GetFiles_WithInvalidPath_ShouldReturnError() + { + // Arrange + string invalidPath = string.Empty; + bool includeHiddenElements = false; + + // Act + ErrorOr> result = _sut.GetFiles(invalidPath, includeHiddenElements); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + } + + [Fact] + public void GetFiles_WhenFileProviderServiceReturnsError_ShouldPropagateError() + { + // Arrange + string path = @"C:\TestDir"; + bool includeHiddenElements = false; + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); + + _mockEnvironmentContext.FileProviderService.GetFilePaths(pathId, includeHiddenElements) + .Returns(Errors.Permission.UnauthorizedAccess); + + // Act + ErrorOr> result = _sut.GetFiles(path, includeHiddenElements); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess); + } + + [Fact] + public void GetFiles_WhenFileDetailsAreInaccessible_ShouldReturnInaccessibleFile() + { + // Arrange + string path = @"C:\TestDir"; + bool includeHiddenElements = false; + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); + FileSystemPathId filePath = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir\InaccessibleFile.txt"); + + _mockEnvironmentContext.FileProviderService.GetFilePaths(pathId, includeHiddenElements) + .Returns(ErrorOrFactory.From(new[] { filePath }.AsEnumerable())); + + _mockEnvironmentContext.FileProviderService.GetFileName(filePath) + .Returns(Errors.Permission.UnauthorizedAccess); + _mockEnvironmentContext.FileProviderService.GetLastWriteTime(filePath) + .Returns(Errors.Permission.UnauthorizedAccess); + _mockEnvironmentContext.FileProviderService.GetCreationTime(filePath) + .Returns(Errors.Permission.UnauthorizedAccess); + _mockEnvironmentContext.FileProviderService.GetSize(filePath) + .Returns(ErrorOrFactory.From((long?)null)); + + // Act + ErrorOr> result = _sut.GetFiles(path, includeHiddenElements); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().HaveCount(1); + result.Value.First().Status.Should().Be(FileSystemItemStatus.Inaccessible); + } + + [Fact] + public void GetFilesOverload_WithValidFile_ShouldReturnListOfFiles() + { + // Arrange + File parentFile = _fileFixture.CreateFile(); + bool includeHiddenElements = false; + FileSystemPathId[] filePaths = + [ + _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir\File1.txt"), + _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir\File2.txt") + ]; + + _mockEnvironmentContext.FileProviderService.GetFilePaths(parentFile.Id, includeHiddenElements) + .Returns(ErrorOrFactory.From(filePaths.AsEnumerable())); + + foreach (FileSystemPathId filePath in filePaths) + { + _mockEnvironmentContext.FileProviderService.GetFileName(filePath) + .Returns(ErrorOrFactory.From(System.IO.Path.GetFileName(filePath.Path))); + _mockEnvironmentContext.FileProviderService.GetLastWriteTime(filePath) + .Returns(ErrorOrFactory.From(Optional.FromNullable(DateTime.Now))); + _mockEnvironmentContext.FileProviderService.GetCreationTime(filePath) + .Returns(ErrorOrFactory.From(Optional.FromNullable(DateTime.Now.AddDays(-1)))); + _mockEnvironmentContext.FileProviderService.GetSize(filePath) + .Returns(ErrorOrFactory.From((long?)1024)); + } + + // Act + ErrorOr> result = _sut.GetFiles(parentFile, includeHiddenElements); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().HaveCount(2); + result.Value.Select(f => f.Name).Should().BeEquivalentTo(["File1.txt", "File2.txt"]); + } + + [Fact] + public void GetFilesOverload_WhenFileProviderServiceReturnsError_ShouldPropagateError() + { + // Arrange + File parentFile = _fileFixture.CreateFile(); + bool includeHiddenElements = false; + + _mockEnvironmentContext.FileProviderService.GetFilePaths(parentFile.Id, includeHiddenElements) + .Returns(Errors.Permission.UnauthorizedAccess); + + // Act + ErrorOr> result = _sut.GetFiles(parentFile, includeHiddenElements); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess); + } + + [Fact] + public void GetFilesOverload_WhenFileDetailsAreInaccessible_ShouldReturnInaccessibleFile() + { + // Arrange + File parentFile = _fileFixture.CreateFile(); + bool includeHiddenElements = false; + FileSystemPathId filePath = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir\InaccessibleFile.txt"); + + _mockEnvironmentContext.FileProviderService.GetFilePaths(parentFile.Id, includeHiddenElements) + .Returns(ErrorOrFactory.From(new[] { filePath }.AsEnumerable())); + + _mockEnvironmentContext.FileProviderService.GetFileName(filePath) + .Returns(Errors.Permission.UnauthorizedAccess); + _mockEnvironmentContext.FileProviderService.GetLastWriteTime(filePath) + .Returns(Errors.Permission.UnauthorizedAccess); + _mockEnvironmentContext.FileProviderService.GetCreationTime(filePath) + .Returns(Errors.Permission.UnauthorizedAccess); + _mockEnvironmentContext.FileProviderService.GetSize(filePath) + .Returns(ErrorOrFactory.From((long?)null)); + + // Act + ErrorOr> result = _sut.GetFiles(parentFile, includeHiddenElements); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().HaveCount(1); + result.Value.First().Status.Should().Be(FileSystemItemStatus.Inaccessible); + } + + [Fact] + public void GetFiles_WithValidFileSystemPathId_ShouldReturnListOfFiles() + { + // Arrange + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir"); + bool includeHiddenElements = false; + FileSystemPathId[] filePaths = + [ + _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir\File1.txt"), + _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir\File2.txt") + ]; + + _mockEnvironmentContext.FileProviderService.GetFilePaths(pathId, includeHiddenElements) + .Returns(ErrorOrFactory.From(filePaths.AsEnumerable())); + + foreach (FileSystemPathId filePath in filePaths) + { + _mockEnvironmentContext.FileProviderService.GetFileName(filePath) + .Returns(ErrorOrFactory.From(System.IO.Path.GetFileName(filePath.Path))); + _mockEnvironmentContext.FileProviderService.GetLastWriteTime(filePath) + .Returns(ErrorOrFactory.From(Optional.FromNullable(DateTime.Now))); + _mockEnvironmentContext.FileProviderService.GetCreationTime(filePath) + .Returns(ErrorOrFactory.From(Optional.FromNullable(DateTime.Now.AddDays(-1)))); + _mockEnvironmentContext.FileProviderService.GetSize(filePath) + .Returns(ErrorOrFactory.From((long?)1024)); + } + + // Act + ErrorOr> result = _sut.GetFiles(pathId, includeHiddenElements); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().HaveCount(2); + result.Value.Select(f => f.Name).Should().BeEquivalentTo(["File1.txt", "File2.txt"]); + } + + [Fact] + public void GetFilesWithFileSystemPathId_WhenFileProviderServiceReturnsError_ShouldPropagateError() + { + // Arrange + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir"); + bool includeHiddenElements = false; + + _mockEnvironmentContext.FileProviderService.GetFilePaths(pathId, includeHiddenElements) + .Returns(Errors.Permission.UnauthorizedAccess); + + // Act + ErrorOr> result = _sut.GetFiles(pathId, includeHiddenElements); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess); + } + + [Fact] + public void GetFilesWithFileSystemPathId_WhenFileDetailsAreInaccessible_ShouldReturnInaccessibleFile() + { + // Arrange + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir"); + bool includeHiddenElements = false; + FileSystemPathId filePath = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir\InaccessibleFile.txt"); + + _mockEnvironmentContext.FileProviderService.GetFilePaths(pathId, includeHiddenElements) + .Returns(ErrorOrFactory.From(new[] { filePath }.AsEnumerable())); + + _mockEnvironmentContext.FileProviderService.GetFileName(filePath) + .Returns(Errors.Permission.UnauthorizedAccess); + _mockEnvironmentContext.FileProviderService.GetLastWriteTime(filePath) + .Returns(Errors.Permission.UnauthorizedAccess); + _mockEnvironmentContext.FileProviderService.GetCreationTime(filePath) + .Returns(Errors.Permission.UnauthorizedAccess); + _mockEnvironmentContext.FileProviderService.GetSize(filePath) + .Returns(ErrorOrFactory.From((long?)null)); + + // Act + ErrorOr> result = _sut.GetFiles(pathId, includeHiddenElements); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().HaveCount(1); + result.Value.First().Status.Should().Be(FileSystemItemStatus.Inaccessible); + } + + [Fact] + public void CopyFile_WithValidPaths_ShouldReturnCopiedFile() + { + // Arrange + string sourcePath = @"C:\Source\file.txt"; + string destinationPath = @"C:\Destination\"; + bool overrideExisting = true; + FileSystemPathId sourcePathId = _fileSystemPathIdFixture.CreateFileSystemPathId(sourcePath); + FileSystemPathId destinationPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(destinationPath); + FileSystemPathId copiedFilePathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Destination\file.txt"); + + _mockPlatformContext.PathStrategy.PathSeparator.Returns('\\'); + _mockPlatformContext.PathStrategy.CombinePath(Arg.Any(), Arg.Any()) + .Returns(copiedFilePathId); + _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((long?)1024); + + // Act + ErrorOr result = _sut.CopyFile(sourcePath, destinationPath, overrideExisting); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Name.Should().Be("file.txt"); + result.Value.Status.Should().Be(FileSystemItemStatus.Accessible); + } + + [Fact] + public void CopyFile_WhenSourceDoesNotExist_ShouldReturnError() + { + // Arrange + string sourcePath = @"C:\Source\nonexistent.txt"; + string destinationPath = @"C:\Destination\"; + bool overrideExisting = true; + FileSystemPathId sourcePathId = _fileSystemPathIdFixture.CreateFileSystemPathId(sourcePath); + + _mockEnvironmentContext.FileProviderService.FileExists(sourcePathId).Returns(ErrorOrFactory.From(false)); + + // Act + ErrorOr result = _sut.CopyFile(sourcePath, destinationPath, overrideExisting); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.FileNotFound); + } + + [Fact] + public void CopyFile_WhenFileProviderServiceReturnsError_ShouldPropagateError() + { + // Arrange + string sourcePath = @"C:\Source\file.txt"; + string destinationPath = @"C:\Destination\"; + bool overrideExisting = true; + FileSystemPathId sourcePathId = _fileSystemPathIdFixture.CreateFileSystemPathId(sourcePath); + FileSystemPathId destinationPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(destinationPath); + + _mockPlatformContext.PathStrategy.PathSeparator.Returns('\\'); + _mockEnvironmentContext.FileProviderService.FileExists(sourcePathId).Returns(ErrorOrFactory.From(true)); + _mockEnvironmentContext.FileProviderService.CopyFile(sourcePathId, destinationPathId, overrideExisting) + .Returns(Errors.Permission.UnauthorizedAccess); + + // Act + ErrorOr result = _sut.CopyFile(sourcePath, destinationPath, overrideExisting); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess); + } + + [Fact] + public void CopyFile_WhenRetrievingFileInfoFails_ShouldReturnInaccessibleFile() + { + // Arrange + string sourcePath = @"C:\Source\file.txt"; + string destinationPath = @"C:\Destination\"; + bool overrideExisting = true; + FileSystemPathId sourcePathId = _fileSystemPathIdFixture.CreateFileSystemPathId(sourcePath); + FileSystemPathId destinationPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(destinationPath); + FileSystemPathId copiedFilePathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Destination\file.txt"); + + _mockPlatformContext.PathStrategy.PathSeparator.Returns('\\'); + _mockEnvironmentContext.FileProviderService.FileExists(sourcePathId).Returns(ErrorOrFactory.From(true)); + _mockEnvironmentContext.FileProviderService.CopyFile(sourcePathId, destinationPathId, overrideExisting) + .Returns(ErrorOrFactory.From(copiedFilePathId)); + + _mockEnvironmentContext.FileProviderService.GetFileName(copiedFilePathId).Returns(Errors.Permission.UnauthorizedAccess); + _mockEnvironmentContext.FileProviderService.GetLastWriteTime(copiedFilePathId).Returns(Errors.Permission.UnauthorizedAccess); + _mockEnvironmentContext.FileProviderService.GetCreationTime(copiedFilePathId).Returns(Errors.Permission.UnauthorizedAccess); + _mockEnvironmentContext.FileProviderService.GetSize(copiedFilePathId).Returns(ErrorOrFactory.From((long?)null)); + + // Act + ErrorOr result = _sut.CopyFile(sourcePath, destinationPath, overrideExisting); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Status.Should().Be(FileSystemItemStatus.Inaccessible); + } + + [Fact] + public void CopyFile_WithInvalidSourcePath_ShouldReturnError() + { + // Arrange + string invalidSourcePath = string.Empty; + string destinationPath = @"C:\Destination\"; + bool overrideExisting = true; + + // Act + ErrorOr result = _sut.CopyFile(invalidSourcePath, destinationPath, overrideExisting); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + } + + [Fact] + public void CopyFile_WithInvalidDestinationPath_ShouldReturnError() + { + // Arrange + string sourcePath = @"C:\Source\file.txt"; + string invalidDestinationPath = string.Empty; + bool overrideExisting = true; + _mockPlatformContext.PathStrategy.PathSeparator.Returns('\\'); + + // Act + ErrorOr result = _sut.CopyFile(sourcePath, invalidDestinationPath, overrideExisting); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + } + + [Fact] + public void CopyFile_WithValidFileSystemPathIds_ShouldReturnCopiedFile() + { + // Arrange + FileSystemPathId sourcePathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Source\file.txt"); + FileSystemPathId destinationPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Destination"); + FileSystemPathId copiedFilePathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Destination\file.txt"); + 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((long?)1024); + + // Act + ErrorOr result = _sut.CopyFile(sourcePathId, destinationPathId, overrideExisting); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Name.Should().Be("file.txt"); + result.Value.Status.Should().Be(FileSystemItemStatus.Accessible); + } + + [Fact] + public void CopyFileWithFileSystemPathIds_WhenSourceDoesNotExist_ShouldReturnError() + { + // Arrange + FileSystemPathId sourcePathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Source\nonexistent.txt"); + FileSystemPathId destinationPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Destination"); + bool overrideExisting = true; + + _mockEnvironmentContext.FileProviderService.FileExists(sourcePathId).Returns(false); + + // Act + ErrorOr result = _sut.CopyFile(sourcePathId, destinationPathId, overrideExisting); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.FileNotFound); + } + + [Fact] + public void CopyFileWithFileSystemPathIds_WhenFileProviderServiceReturnsError_ShouldPropagateError() + { + // Arrange + FileSystemPathId sourcePathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Source\file.txt"); + FileSystemPathId destinationPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Destination"); + bool overrideExisting = true; + + _mockEnvironmentContext.FileProviderService.FileExists(sourcePathId).Returns(true); + _mockEnvironmentContext.FileProviderService.CopyFile(sourcePathId, destinationPathId, overrideExisting) + .Returns(Errors.Permission.UnauthorizedAccess); + + // Act + ErrorOr result = _sut.CopyFile(sourcePathId, destinationPathId, overrideExisting); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess); + } + + [Fact] + public void CopyFileWithFileSystemPathIds_WhenRetrievingFileInfoFails_ShouldReturnInaccessibleFile() + { + // Arrange + FileSystemPathId sourcePathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Source\file.txt"); + FileSystemPathId destinationPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Destination"); + FileSystemPathId copiedFilePathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Destination\file.txt"); + bool overrideExisting = true; + + _mockEnvironmentContext.FileProviderService.FileExists(sourcePathId).Returns(true); + _mockEnvironmentContext.FileProviderService.CopyFile(sourcePathId, destinationPathId, overrideExisting) + .Returns(copiedFilePathId); + + _mockEnvironmentContext.FileProviderService.GetFileName(copiedFilePathId).Returns(Errors.Permission.UnauthorizedAccess); + _mockEnvironmentContext.FileProviderService.GetLastWriteTime(copiedFilePathId).Returns(Errors.Permission.UnauthorizedAccess); + _mockEnvironmentContext.FileProviderService.GetCreationTime(copiedFilePathId).Returns(Errors.Permission.UnauthorizedAccess); + _mockEnvironmentContext.FileProviderService.GetSize(copiedFilePathId).Returns(ErrorOrFactory.From((long?)null)); + + // Act + ErrorOr result = _sut.CopyFile(sourcePathId, destinationPathId, overrideExisting); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Status.Should().Be(FileSystemItemStatus.Inaccessible); + } + + [Fact] + public void MoveFile_WithValidPaths_ShouldReturnMovedFile() + { + // Arrange + string sourcePath = @"C:\Source\file.txt"; + string destinationPath = @"C:\Destination\"; + bool overrideExisting = true; + FileSystemPathId sourcePathId = _fileSystemPathIdFixture.CreateFileSystemPathId(sourcePath); + FileSystemPathId destinationPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(destinationPath); + FileSystemPathId movedFilePathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Destination\file.txt"); + + _mockPlatformContext.PathStrategy.PathSeparator.Returns('\\'); + _mockPlatformContext.PathStrategy.CombinePath(Arg.Any(), Arg.Any()) + .Returns(movedFilePathId); + _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((long?)1024); + + // Act + ErrorOr result = _sut.MoveFile(sourcePath, destinationPath, overrideExisting); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Name.Should().Be("file.txt"); + result.Value.Status.Should().Be(FileSystemItemStatus.Accessible); + } + + [Fact] + public void MoveFile_WhenSourceDoesNotExist_ShouldReturnError() + { + // Arrange + string sourcePath = @"C:\Source\nonexistent.txt"; + string destinationPath = @"C:\Destination"; + bool overrideExisting = true; + FileSystemPathId sourcePathId = _fileSystemPathIdFixture.CreateFileSystemPathId(sourcePath); + + _mockPlatformContext.PathStrategy.PathSeparator.Returns('\\'); + _mockEnvironmentContext.FileProviderService.FileExists(sourcePathId).Returns(false); + + // Act + ErrorOr result = _sut.MoveFile(sourcePath, destinationPath, overrideExisting); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.FileNotFound); + } + + [Fact] + public void MoveFile_WhenFileProviderServiceReturnsError_ShouldPropagateError() + { + // Arrange + string sourcePath = @"C:\Source\file.txt"; + string destinationPath = @"C:\Destination\"; + bool overrideExisting = true; + FileSystemPathId sourcePathId = _fileSystemPathIdFixture.CreateFileSystemPathId(sourcePath); + FileSystemPathId destinationPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(destinationPath); + + _mockPlatformContext.PathStrategy.PathSeparator.Returns('\\'); + _mockEnvironmentContext.FileProviderService.FileExists(sourcePathId).Returns(true); + _mockEnvironmentContext.FileProviderService.MoveFile(sourcePathId, destinationPathId, overrideExisting) + .Returns(Errors.Permission.UnauthorizedAccess); + + // Act + ErrorOr result = _sut.MoveFile(sourcePath, destinationPath, overrideExisting); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess); + } + + [Fact] + public void MoveFile_WhenRetrievingFileInfoFails_ShouldReturnInaccessibleFile() + { + // Arrange + string sourcePath = @"C:\Source\file.txt"; + string destinationPath = @"C:\Destination\"; + bool overrideExisting = true; + FileSystemPathId sourcePathId = _fileSystemPathIdFixture.CreateFileSystemPathId(sourcePath); + FileSystemPathId destinationPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(destinationPath); + FileSystemPathId movedFilePathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Destination\file.txt"); + + _mockPlatformContext.PathStrategy.PathSeparator.Returns('\\'); + _mockPlatformContext.PathStrategy.CombinePath(Arg.Any(), Arg.Any()) + .Returns(movedFilePathId); + _mockEnvironmentContext.FileProviderService.FileExists(sourcePathId).Returns(true); + _mockEnvironmentContext.FileProviderService.MoveFile(sourcePathId, destinationPathId, overrideExisting) + .Returns(movedFilePathId); + + _mockEnvironmentContext.FileProviderService.GetFileName(movedFilePathId).Returns(Errors.Permission.UnauthorizedAccess); + _mockEnvironmentContext.FileProviderService.GetLastWriteTime(movedFilePathId).Returns(Errors.Permission.UnauthorizedAccess); + _mockEnvironmentContext.FileProviderService.GetCreationTime(movedFilePathId).Returns(Errors.Permission.UnauthorizedAccess); + _mockEnvironmentContext.FileProviderService.GetSize(movedFilePathId).Returns(ErrorOrFactory.From((long?)null)); + + // Act + ErrorOr result = _sut.MoveFile(sourcePath, destinationPath, overrideExisting); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Status.Should().Be(FileSystemItemStatus.Inaccessible); + } + + [Fact] + public void MoveFile_WithInvalidSourcePath_ShouldReturnError() + { + // Arrange + string invalidSourcePath = string.Empty; + string destinationPath = @"C:\Destination\"; + bool overrideExisting = true; + + _mockPlatformContext.PathStrategy.PathSeparator.Returns('\\'); + + // Act + ErrorOr result = _sut.MoveFile(invalidSourcePath, destinationPath, overrideExisting); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + } + + [Fact] + public void MoveFile_WithInvalidDestinationPath_ShouldReturnError() + { + // Arrange + string sourcePath = @"C:\Source\file.txt"; + string invalidDestinationPath = string.Empty; + bool overrideExisting = true; + + _mockPlatformContext.PathStrategy.PathSeparator.Returns('\\'); + + // Act + ErrorOr result = _sut.MoveFile(sourcePath, invalidDestinationPath, overrideExisting); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + } + + [Fact] + public void MoveFile_WithValidFileSystemPathIds_ShouldReturnMovedFile() + { + // Arrange + FileSystemPathId sourcePathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Source\file.txt"); + FileSystemPathId destinationPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Destination"); + FileSystemPathId movedFilePathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Destination\file.txt"); + 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((long?)1024); + + // Act + ErrorOr result = _sut.MoveFile(sourcePathId, destinationPathId, overrideExisting); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Name.Should().Be("file.txt"); + result.Value.Status.Should().Be(FileSystemItemStatus.Accessible); + } + + [Fact] + public void MoveFileWithFileSystemPathIds_WhenSourceDoesNotExist_ShouldReturnError() + { + // Arrange + FileSystemPathId sourcePathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Source\nonexistent.txt"); + FileSystemPathId destinationPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Destination"); + bool overrideExisting = true; + + _mockEnvironmentContext.FileProviderService.FileExists(sourcePathId).Returns(false); + + // Act + ErrorOr result = _sut.MoveFile(sourcePathId, destinationPathId, overrideExisting); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.FileNotFound); + } + + [Fact] + public void MoveFileWithFileSystemPathIds_WhenFileProviderServiceReturnsError_ShouldPropagateError() + { + // Arrange + FileSystemPathId sourcePathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Source\file.txt"); + FileSystemPathId destinationPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Destination\"); + bool overrideExisting = true; + + _mockEnvironmentContext.FileProviderService.FileExists(sourcePathId).Returns(true); + _mockEnvironmentContext.FileProviderService.MoveFile(sourcePathId, destinationPathId, overrideExisting) + .Returns(Errors.Permission.UnauthorizedAccess); + + // Act + ErrorOr result = _sut.MoveFile(sourcePathId, destinationPathId, overrideExisting); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess); + } + + [Fact] + public void MoveFileWithFileSystemPathIds_WhenRetrievingFileInfoFails_ShouldReturnInaccessibleFile() + { + // Arrange + FileSystemPathId sourcePathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Source\file.txt"); + FileSystemPathId destinationPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Destination\"); + FileSystemPathId movedFilePathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Destination\file.txt"); + bool overrideExisting = true; + + _mockEnvironmentContext.FileProviderService.FileExists(sourcePathId).Returns(true); + _mockEnvironmentContext.FileProviderService.MoveFile(sourcePathId, destinationPathId, overrideExisting) + .Returns(movedFilePathId); + + _mockEnvironmentContext.FileProviderService.GetFileName(movedFilePathId).Returns(Errors.Permission.UnauthorizedAccess); + _mockEnvironmentContext.FileProviderService.GetLastWriteTime(movedFilePathId).Returns(Errors.Permission.UnauthorizedAccess); + _mockEnvironmentContext.FileProviderService.GetCreationTime(movedFilePathId).Returns(Errors.Permission.UnauthorizedAccess); + _mockEnvironmentContext.FileProviderService.GetSize(movedFilePathId).Returns(ErrorOrFactory.From((long?)null)); + + // Act + ErrorOr result = _sut.MoveFile(sourcePathId, destinationPathId, overrideExisting); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Status.Should().Be(FileSystemItemStatus.Inaccessible); + } + + [Fact] + public void MoveFile_WhenFileExistsReturnsError_ShouldPropagateError() + { + // Arrange + string sourcePath = @"C:\Source\file.txt"; + string destinationPath = @"C:\Destination\"; + bool overrideExisting = true; + FileSystemPathId sourcePathId = _fileSystemPathIdFixture.CreateFileSystemPathId(sourcePath); + + _mockPlatformContext.PathStrategy.PathSeparator.Returns('\\'); + _mockEnvironmentContext.FileProviderService.FileExists(sourcePathId) + .Returns(Errors.Permission.UnauthorizedAccess); + + // Act + ErrorOr result = _sut.MoveFile(sourcePath, destinationPath, overrideExisting); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess); + } + + [Fact] + public void RenameFile_WithValidPathAndName_ShouldReturnRenamedFile() + { + // Arrange + string path = @"C:\Source\oldfile.txt"; + string newName = "newfile.txt"; + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); + FileSystemPathId newPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Source\newfile.txt"); + + _mockPlatformContext.PathStrategy.PathSeparator.Returns('\\'); + _mockPlatformContext.PathStrategy.CombinePath(Arg.Any(), newName) + .Returns(ErrorOrFactory.From(newPathId)); + _mockEnvironmentContext.FileProviderService.FileExists(newPathId).Returns(false); + _mockEnvironmentContext.FileProviderService.RenameFile(pathId, newName) + .Returns(ErrorOrFactory.From(newPathId)); + _mockEnvironmentContext.FileProviderService.GetFileName(newPathId).Returns(ErrorOrFactory.From(newName)); + _mockEnvironmentContext.FileProviderService.GetLastWriteTime(newPathId) + .Returns(ErrorOrFactory.From(Optional.FromNullable(DateTime.Now))); + _mockEnvironmentContext.FileProviderService.GetCreationTime(newPathId) + .Returns(ErrorOrFactory.From(Optional.FromNullable(DateTime.Now.AddDays(-1)))); + _mockEnvironmentContext.FileProviderService.GetSize(newPathId).Returns(ErrorOrFactory.From((long?)1024)); + + // Act + ErrorOr result = _sut.RenameFile(path, newName); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Name.Should().Be(newName); + result.Value.Status.Should().Be(FileSystemItemStatus.Accessible); + } + + [Fact] + public void RenameFile_WhenNewNameAlreadyExists_ShouldReturnError() + { + // Arrange + string path = @"C:\Source\oldfile.txt"; + string newName = "existingfile.txt"; + FileSystemPathId newPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Source\existingfile.txt"); + + _mockPlatformContext.PathStrategy.PathSeparator.Returns('\\'); + _mockPlatformContext.PathStrategy.CombinePath(Arg.Any(), newName) + .Returns(ErrorOrFactory.From(newPathId)); + _mockEnvironmentContext.FileProviderService.FileExists(newPathId).Returns(true); + + // Act + ErrorOr result = _sut.RenameFile(path, newName); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.FileAlreadyExists); + } + + [Fact] + public void RenameFile_WhenFileProviderServiceReturnsError_ShouldPropagateError() + { + // Arrange + string path = @"C:\Source\oldfile.txt"; + string newName = "newfile.txt"; + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); + FileSystemPathId newPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Source\newfile.txt"); + + _mockPlatformContext.PathStrategy.PathSeparator.Returns('\\'); + _mockPlatformContext.PathStrategy.CombinePath(Arg.Any(), newName) + .Returns(ErrorOrFactory.From(newPathId)); + _mockEnvironmentContext.FileProviderService.FileExists(newPathId).Returns(false); + _mockEnvironmentContext.FileProviderService.RenameFile(pathId, newName) + .Returns(Errors.Permission.UnauthorizedAccess); + + // Act + ErrorOr result = _sut.RenameFile(path, newName); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess); + } + + [Fact] + public void RenameFile_WhenRetrievingFileInfoFails_ShouldReturnInaccessibleFile() + { + // Arrange + string path = @"C:\Source\oldfile.txt"; + string newName = "newfile.txt"; + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); + FileSystemPathId newPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Source\newfile.txt"); + + _mockPlatformContext.PathStrategy.PathSeparator.Returns('\\'); + _mockPlatformContext.PathStrategy.CombinePath(Arg.Any(), newName) + .Returns(ErrorOrFactory.From(newPathId)); + _mockEnvironmentContext.FileProviderService.FileExists(newPathId).Returns(false); + _mockEnvironmentContext.FileProviderService.RenameFile(pathId, newName) + .Returns(ErrorOrFactory.From(newPathId)); + + _mockEnvironmentContext.FileProviderService.GetFileName(newPathId).Returns(Errors.Permission.UnauthorizedAccess); + _mockEnvironmentContext.FileProviderService.GetLastWriteTime(newPathId).Returns(Errors.Permission.UnauthorizedAccess); + _mockEnvironmentContext.FileProviderService.GetCreationTime(newPathId).Returns(Errors.Permission.UnauthorizedAccess); + _mockEnvironmentContext.FileProviderService.GetSize(newPathId).Returns(ErrorOrFactory.From((long?)null)); + + // Act + ErrorOr result = _sut.RenameFile(path, newName); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Status.Should().Be(FileSystemItemStatus.Inaccessible); + } + + [Fact] + public void RenameFile_WithInvalidPath_ShouldReturnError() + { + // Arrange + string invalidPath = string.Empty; + string newName = "newfile.txt"; + + _mockPlatformContext.PathStrategy.PathSeparator.Returns('\\'); + + // Act + ErrorOr result = _sut.RenameFile(invalidPath, newName); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + } + + [Fact] + public void RenameFileWithValidFileSystemPathIdAndName_ShouldReturnRenamedFile() + { + // Arrange + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Source\oldfile.txt"); + string newName = "newfile.txt"; + FileSystemPathId newPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Source\newfile.txt"); + + _mockPlatformContext.PathStrategy.CombinePath(Arg.Any(), newName) + .Returns(ErrorOrFactory.From(newPathId)); + _mockEnvironmentContext.FileProviderService.FileExists(newPathId).Returns(false); + _mockEnvironmentContext.FileProviderService.RenameFile(pathId, newName) + .Returns(ErrorOrFactory.From(newPathId)); + _mockEnvironmentContext.FileProviderService.GetFileName(newPathId).Returns(ErrorOrFactory.From(newName)); + _mockEnvironmentContext.FileProviderService.GetLastWriteTime(newPathId) + .Returns(ErrorOrFactory.From(Optional.FromNullable(DateTime.Now))); + _mockEnvironmentContext.FileProviderService.GetCreationTime(newPathId) + .Returns(ErrorOrFactory.From(Optional.FromNullable(DateTime.Now.AddDays(-1)))); + _mockEnvironmentContext.FileProviderService.GetSize(newPathId).Returns(ErrorOrFactory.From((long?)1024)); + + // Act + ErrorOr result = _sut.RenameFile(pathId, newName); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Name.Should().Be(newName); + result.Value.Status.Should().Be(FileSystemItemStatus.Accessible); + } + + [Fact] + public void RenameFileWithFileSystemPathId_WhenNewNameAlreadyExists_ShouldReturnError() + { + // Arrange + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Source\oldfile.txt"); + string newName = "existingfile.txt"; + FileSystemPathId newPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Source\existingfile.txt"); + + _mockPlatformContext.PathStrategy.CombinePath(Arg.Any(), newName) + .Returns(ErrorOrFactory.From(newPathId)); + _mockEnvironmentContext.FileProviderService.FileExists(newPathId).Returns(true); + + // Act + ErrorOr result = _sut.RenameFile(pathId, newName); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.FileAlreadyExists); + } + + [Fact] + public void RenameFileWithFileSystemPathId_WhenFileProviderServiceReturnsError_ShouldPropagateError() + { + // Arrange + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Source\oldfile.txt"); + string newName = "newfile.txt"; + FileSystemPathId newPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Source\newfile.txt"); + + _mockPlatformContext.PathStrategy.CombinePath(Arg.Any(), newName) + .Returns(ErrorOrFactory.From(newPathId)); + _mockEnvironmentContext.FileProviderService.FileExists(newPathId).Returns(false); + _mockEnvironmentContext.FileProviderService.RenameFile(pathId, newName) + .Returns(Errors.Permission.UnauthorizedAccess); + + // Act + ErrorOr result = _sut.RenameFile(pathId, newName); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess); + } + + [Fact] + public void RenameFileWithFileSystemPathId_WhenRetrievingFileInfoFails_ShouldReturnInaccessibleFile() + { + // Arrange + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Source\oldfile.txt"); + string newName = "newfile.txt"; + FileSystemPathId newPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Source\newfile.txt"); + + _mockPlatformContext.PathStrategy.CombinePath(Arg.Any(), newName) + .Returns(ErrorOrFactory.From(newPathId)); + _mockEnvironmentContext.FileProviderService.FileExists(newPathId).Returns(false); + _mockEnvironmentContext.FileProviderService.RenameFile(pathId, newName) + .Returns(ErrorOrFactory.From(newPathId)); + + _mockEnvironmentContext.FileProviderService.GetFileName(newPathId).Returns(Errors.Permission.UnauthorizedAccess); + _mockEnvironmentContext.FileProviderService.GetLastWriteTime(newPathId).Returns(Errors.Permission.UnauthorizedAccess); + _mockEnvironmentContext.FileProviderService.GetCreationTime(newPathId).Returns(Errors.Permission.UnauthorizedAccess); + _mockEnvironmentContext.FileProviderService.GetSize(newPathId).Returns(ErrorOrFactory.From((long?)null)); + + // Act + ErrorOr result = _sut.RenameFile(pathId, newName); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Status.Should().Be(FileSystemItemStatus.Inaccessible); + } + + [Fact] + public void RenameFile_WhenCombinePathReturnsError_ShouldPropagateError() + { + // Arrange + string path = @"C:\Source\oldfile.txt"; + string newName = "newfile.txt"; + + _mockPlatformContext.PathStrategy.PathSeparator.Returns('\\'); + _mockPlatformContext.PathStrategy.CombinePath(Arg.Any(), newName) + .Returns(Errors.FileManagement.InvalidPath); + + // Act + ErrorOr result = _sut.RenameFile(path, newName); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + } + + [Fact] + public void RenameFile_WhenFileExistsReturnsError_ShouldPropagateError() + { + // Arrange + string path = @"C:\Source\oldfile.txt"; + string newName = "newfile.txt"; + FileSystemPathId newPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Source\newfile.txt"); + + _mockPlatformContext.PathStrategy.PathSeparator.Returns('\\'); + _mockPlatformContext.PathStrategy.CombinePath(Arg.Any(), newName) + .Returns(ErrorOrFactory.From(newPathId)); + _mockEnvironmentContext.FileProviderService.FileExists(newPathId) + .Returns(Errors.Permission.UnauthorizedAccess); + + // Act + ErrorOr result = _sut.RenameFile(path, newName); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess); + } + + [Fact] + public void RenameFileWithFileSystemPathId_WhenCombinePathReturnsError_ShouldPropagateError() + { + // Arrange + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Source\oldfile.txt"); + string newName = "newfile.txt"; + + _mockPlatformContext.PathStrategy.CombinePath(Arg.Any(), newName) + .Returns(Errors.FileManagement.InvalidPath); + + // Act + ErrorOr result = _sut.RenameFile(pathId, newName); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + } + + [Fact] + public void RenameFileWithFileSystemPathId_WhenFileExistsReturnsError_ShouldPropagateError() + { + // Arrange + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Source\oldfile.txt"); + string newName = "newfile.txt"; + FileSystemPathId newPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Source\newfile.txt"); + + _mockPlatformContext.PathStrategy.CombinePath(Arg.Any(), newName) + .Returns(ErrorOrFactory.From(newPathId)); + _mockEnvironmentContext.FileProviderService.FileExists(newPathId) + .Returns(Errors.Permission.UnauthorizedAccess); + + // Act + ErrorOr result = _sut.RenameFile(pathId, newName); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess); + } + + [Fact] + public void DeleteFile_WithValidPath_ShouldReturnDeleted() + { + // Arrange + string path = @"C:\Source\file.txt"; + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); + + _mockEnvironmentContext.FileProviderService.DeleteFile(pathId) + .Returns(Result.Deleted); + + // Act + ErrorOr result = _sut.DeleteFile(path); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().Be(Result.Deleted); + } + + [Fact] + public void DeleteFile_WithInvalidPath_ShouldReturnError() + { + // Arrange + string invalidPath = string.Empty; + + // Act + ErrorOr result = _sut.DeleteFile(invalidPath); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + } + + [Fact] + public void DeleteFile_WhenFileProviderServiceReturnsError_ShouldPropagateError() + { + // Arrange + string path = @"C:\Source\file.txt"; + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); + + _mockEnvironmentContext.FileProviderService.DeleteFile(pathId) + .Returns(Errors.Permission.UnauthorizedAccess); + + // Act + ErrorOr result = _sut.DeleteFile(path); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess); + } + + [Fact] + public void DeleteFile_WithValidFileSystemPathId_ShouldReturnDeleted() + { + // Arrange + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Source\file.txt"); + + _mockEnvironmentContext.FileProviderService.DeleteFile(pathId) + .Returns(Result.Deleted); + + // Act + ErrorOr result = _sut.DeleteFile(pathId); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().Be(Result.Deleted); + } + + [Fact] + public void DeleteFileWithFileSystemPathId_WhenFileProviderServiceReturnsError_ShouldPropagateError() + { + // Arrange + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Source\file.txt"); + + _mockEnvironmentContext.FileProviderService.DeleteFile(pathId) + .Returns(Errors.Permission.UnauthorizedAccess); + + // Act + ErrorOr result = _sut.DeleteFile(pathId); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Services/FileTypeServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Services/FileTypeServiceTests.cs new file mode 100644 index 00000000..4e79fed1 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Services/FileTypeServiceTests.cs @@ -0,0 +1,237 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FluentAssertions; +using Lumina.Contracts.Enums.FileSystem; +using Lumina.Contracts.Enums.PhotoLibrary; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Entities.Fixtures; +using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects.Fixtures; +using NSubstitute; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO.Abstractions.TestingHelpers; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Services; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class FileTypeServiceTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private MockFileSystem _mockFileSystem = null!; + private readonly IFileSystemPermissionsService _mockFileSystemPermissionsService; + private FileTypeService? sut; + private readonly FileSystemPathIdFixture _fileSystemPathIdFixture; + private readonly FileFixture _fileFixture; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public FileTypeServiceTests() + { + _mockFileSystemPermissionsService = Substitute.For(); + _fileSystemPathIdFixture = new FileSystemPathIdFixture(); + _fileFixture = new FileFixture(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public async Task GetImageTypeAsync_WithValidFile_ShouldReturnCorrectImageType() + { + // Arrange + File file = _fileFixture.CreateFile(); + byte[] pngHeader = [137, 80, 78, 71, 13, 10, 26, 10]; + byte[] fileContent = [.. pngHeader, .. Enumerable.Repeat(0, 100)]; + + SetupMockFileSystem(file.Id, fileContent); + sut = new FileTypeService(_mockFileSystem, _mockFileSystemPermissionsService); + _mockFileSystemPermissionsService.CanAccessPath(file.Id, FileAccessMode.ReadContents).Returns(true); + + // Act + ErrorOr result = await sut.GetImageTypeAsync(file, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().Be(ImageType.PNG); + } + + [Fact] + public async Task GetImageTypeAsync_WithUnauthorizedAccess_ShouldReturnError() + { + // Arrange + File file = _fileFixture.CreateFile(); + + SetupMockFileSystem(file.Id, []); + sut = new FileTypeService(_mockFileSystem, _mockFileSystemPermissionsService); + + _mockFileSystemPermissionsService.CanAccessPath(file.Id, FileAccessMode.ReadContents).Returns(false); + + // Act + ErrorOr result = await sut.GetImageTypeAsync(file, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess); + } + + [Fact] + public async Task GetImageTypeAsync_WithSmallFile_ShouldReturnNone() + { + // Arrange + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\test.jpg"); + byte[] fileContent = [1, 2, 3]; // Less than BUFFER_SIZE + + SetupMockFileSystem(pathId, fileContent); + sut = new FileTypeService(_mockFileSystem, _mockFileSystemPermissionsService); + _mockFileSystemPermissionsService.CanAccessPath(pathId, FileAccessMode.ReadContents).Returns(true); + + // Act + ErrorOr result = await sut.GetImageTypeAsync(pathId, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().Be(ImageType.None); + } + + [Fact] + public async Task GetImageTypeAsync_WithSvgFile_ShouldReturnSvgType() + { + // Arrange + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\test.svg"); + string svgContent = ""; + byte[] fileContent = Encoding.UTF8.GetBytes(svgContent); + + SetupMockFileSystem(pathId, fileContent); + sut = new FileTypeService(_mockFileSystem, _mockFileSystemPermissionsService); + _mockFileSystemPermissionsService.CanAccessPath(pathId, FileAccessMode.ReadContents).Returns(true); + + // Act + ErrorOr result = await sut.GetImageTypeAsync(pathId, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().Be(ImageType.SVG); + } + + [Fact] + public async Task GetImageTypeAsync_WithTgaFile_ShouldReturnTgaType() + { + // Arrange + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\test.tga"); + byte[] tgaHeader = new byte[18]; + tgaHeader[2] = 2; // Set image type to 2 (uncompressed true-color image) + byte[] fileContent = [.. tgaHeader, .. Enumerable.Repeat(0, 100)]; + + SetupMockFileSystem(pathId, fileContent); + sut = new FileTypeService(_mockFileSystem, _mockFileSystemPermissionsService); + + _mockFileSystemPermissionsService.CanAccessPath(pathId, FileAccessMode.ReadContents).Returns(true); + + // Act + ErrorOr result = await sut.GetImageTypeAsync(pathId, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().Be(ImageType.TGA); + } + + [Fact] + public async Task GetImageTypeAsync_WithUnknownImageType_ShouldReturnNone() + { + // Arrange + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\test.unknown"); + byte[] fileContent = Enumerable.Repeat(0, 100).ToArray(); + + SetupMockFileSystem(pathId, fileContent); + sut = new FileTypeService(_mockFileSystem, _mockFileSystemPermissionsService); + _mockFileSystemPermissionsService.CanAccessPath(pathId, FileAccessMode.ReadContents).Returns(true); + + // Act + ErrorOr result = await sut.GetImageTypeAsync(pathId, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().Be(ImageType.None); + } + + private void SetupMockFileSystem(FileSystemPathId pathId, byte[] fileContent) + { + MockFileSystem mockFileSystem = new(new Dictionary + { + { pathId.Path, new MockFileData(fileContent) } + }); + + _mockFileSystem = mockFileSystem; + } + + [Fact] + public async Task GetImageTypeAsync_WithSvgFileStartingWithXmlDeclaration_ShouldReturnSvgType() + { + // Arrange + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\test.svg"); + string svgContent = "\n"; + byte[] fileContent = Encoding.UTF8.GetBytes(svgContent); + + SetupMockFileSystem(pathId, fileContent); + sut = new FileTypeService(_mockFileSystem, _mockFileSystemPermissionsService); + + _mockFileSystemPermissionsService.CanAccessPath(pathId, FileAccessMode.ReadContents).Returns(true); + + // Act + ErrorOr result = await sut.GetImageTypeAsync(pathId, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().Be(ImageType.SVG); + } + + [Theory] + [InlineData(new byte[] { 66, 77 }, ImageType.BMP, "BMP")] + [InlineData(new byte[] { 71, 73, 70 }, ImageType.GIF, "GIF")] + [InlineData(new byte[] { 137, 80, 78, 71 }, ImageType.PNG, "PNG")] + [InlineData(new byte[] { 73, 73, 42 }, ImageType.TIFF, "TIFF (Little Endian)")] + [InlineData(new byte[] { 77, 77, 42 }, ImageType.TIFF, "TIFF (Big Endian)")] + [InlineData(new byte[] { 255, 216, 255, 224 }, ImageType.JPEG, "JPEG")] + [InlineData(new byte[] { 255, 216, 255, 225 }, ImageType.JPEG_CANON, "JPEG (Canon)")] + [InlineData(new byte[] { 255, 216, 255, 226 }, ImageType.JPEG_UNKNOWN, "JPEG (Unknown)")] + [InlineData(new byte[] { 0x00, 0x11, 0x02, 0xFF }, ImageType.PICT, "PICT")] + [InlineData(new byte[] { 0x00, 0x00, 0x01, 0x00 }, ImageType.ICO, "ICO")] + [InlineData(new byte[] { 0x38, 0x42, 0x50, 0x53 }, ImageType.PSD, "PSD")] + [InlineData(new byte[] { 0xFF, 0x4F, 0xFF, 0x51 }, ImageType.JPEG2000, "JPEG 2000")] + [InlineData(new byte[] { 0x00, 0x00, 0x00, 0x0C, 0x6A, 0x70, 0x20, 0x20 }, ImageType.AVIF, "AVIF")] + [InlineData(new byte[] { 0x00, 0x00, 0x00, 0x0C, 0x6A, 0x50, 0x20, 0x20 }, ImageType.JPEG2000, "JPEG 2000 (variant)")] + [InlineData(new byte[] { 0x52, 0x49, 0x46, 0x46, 0x00, 0x00, 0x00, 0x00, 0x57, 0x45, 0x42, 0x50 }, ImageType.WEBP, "WEBP")] + [InlineData(new byte[] { 0x00, 0x00, 0x00, 0x00 }, ImageType.None, "Unknown")] + public async Task GetImageTypeAsync_WithVariousImageTypes_ShouldIdentifyCorrectly(byte[] header, ImageType expectedType, string testName) + { + // Arrange + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId($@"C:\test.{testName.ToLower()}"); + byte[] fileContent = [.. header, .. Enumerable.Repeat(0, 100)]; + + SetupMockFileSystem(pathId, fileContent); + sut = new FileTypeService(_mockFileSystem, _mockFileSystemPermissionsService); + + _mockFileSystemPermissionsService.CanAccessPath(pathId, FileAccessMode.ReadContents).Returns(true); + + // Act + ErrorOr result = await sut.GetImageTypeAsync(pathId, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().Be(expectedType, because: $"the file header matches {testName}"); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Services/Fixtures/ImageTypeFixture.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Services/Fixtures/ImageTypeFixture.cs new file mode 100644 index 00000000..0b9d19fe --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Services/Fixtures/ImageTypeFixture.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Enums.PhotoLibrary; +using SixLabors.ImageSharp; +using SixLabors.ImageSharp.Formats; +using SixLabors.ImageSharp.Formats.Bmp; +using SixLabors.ImageSharp.Formats.Gif; +using SixLabors.ImageSharp.Formats.Jpeg; +using SixLabors.ImageSharp.Formats.Png; +using SixLabors.ImageSharp.PixelFormats; +using System.Diagnostics.CodeAnalysis; +using System.IO; +#endregion + +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Services.Fixtures; + +/// +/// Fixture class for the enum. +/// +[ExcludeFromCodeCoverage] +public class ImageTypeFixture : TheoryData +{ + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public ImageTypeFixture() + { + Add(ImageType.JPEG, CreateImage(new JpegEncoder())); + Add(ImageType.PNG, CreateImage(new PngEncoder())); + Add(ImageType.BMP, CreateImage(new BmpEncoder())); + Add(ImageType.GIF, CreateImage(new GifEncoder())); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + /// + /// Creates a byte array representing a thumbnail fixture. + /// + /// The encoder used for the image. + /// The byte array of the created image. + private static byte[] CreateImage(IImageEncoder encoder) + { + using Image image = new(10, 10); + using MemoryStream ms = new(); + image.Save(ms, encoder); + return ms.ToArray(); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Services/PathServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Services/PathServiceTests.cs new file mode 100644 index 00000000..2f19c721 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Services/PathServiceTests.cs @@ -0,0 +1,500 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FluentAssertions; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Path; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects.Fixtures; +using NSubstitute; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Services; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class PathServiceTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly IPlatformContextManager _mockPlatformContextManager; + private readonly IPlatformContext _mockPlatformContext; + private readonly IPathStrategy _mockPathStrategy; + private readonly PathService _sut; + private readonly FileSystemPathIdFixture _fileSystemPathIdFixture; + private readonly PathSegmentFixture _pathSegmentFixture; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public PathServiceTests() + { + _mockPlatformContextManager = Substitute.For(); + _mockPlatformContext = Substitute.For(); + _mockPathStrategy = Substitute.For(); + _mockPlatformContext.PathStrategy.Returns(_mockPathStrategy); + _mockPlatformContextManager.GetCurrentContext().Returns(_mockPlatformContext); + _sut = new PathService(_mockPlatformContextManager); + _fileSystemPathIdFixture = new FileSystemPathIdFixture(); + _pathSegmentFixture = new PathSegmentFixture(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public void IsValidPath_WithValidPath_ShouldReturnTrue() + { + // Arrange + string validPath = @"C:\ValidPath"; + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(validPath); + _mockPathStrategy.IsValidPath(pathId).Returns(true); + + // Act + bool result = _sut.IsValidPath(validPath); + + // Assert + result.Should().BeTrue(); + _mockPathStrategy.Received(1).IsValidPath(Arg.Is(id => id.Path == validPath)); + } + + [Fact] + public void IsValidPath_WithInvalidPath_ShouldReturnFalse() + { + // Arrange + string invalidPath = @"C:\Invalid\*Path"; + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(invalidPath); + _mockPathStrategy.IsValidPath(pathId).Returns(false); + + // Act + bool result = _sut.IsValidPath(invalidPath); + + // Assert + result.Should().BeFalse(); + _mockPathStrategy.Received(1).IsValidPath(Arg.Is(id => id.Path == invalidPath)); + } + + [Fact] + public void IsValidPath_WithEmptyPath_ShouldReturnFalse() + { + // Arrange + string emptyPath = string.Empty; + + // Act + bool result = _sut.IsValidPath(emptyPath); + + // Assert + result.Should().BeFalse(); + _mockPathStrategy.DidNotReceive().IsValidPath(Arg.Any()); + } + + [Fact] + public void IsValidPath_WithNullPath_ShouldReturnFalse() + { + // Arrange + string? nullPath = null; + + // Act + bool result = _sut.IsValidPath(nullPath!); + + // Assert + result.Should().BeFalse(); + _mockPathStrategy.DidNotReceive().IsValidPath(Arg.Any()); + } + + [Fact] + public void Exists_WithValidExistingPath_ShouldReturnTrue() + { + // Arrange + string existingPath = @"C:\ExistingPath"; + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(existingPath); + _mockPathStrategy.Exists(pathId).Returns(true); + + // Act + bool result = _sut.Exists(existingPath); + + // Assert + result.Should().BeTrue(); + _mockPathStrategy.Received(1).Exists(Arg.Is(id => id.Path == existingPath)); + } + + [Fact] + public void Exists_WithValidNonExistingPath_ShouldReturnFalse() + { + // Arrange + string nonExistingPath = @"C:\NonExistingPath"; + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(nonExistingPath); + _mockPathStrategy.Exists(pathId).Returns(false); + + // Act + bool result = _sut.Exists(nonExistingPath); + + // Assert + result.Should().BeFalse(); + _mockPathStrategy.Received(1).Exists(Arg.Is(id => id.Path == nonExistingPath)); + } + + [Fact] + public void Exists_WithEmptyPath_ShouldReturnFalse() + { + // Arrange + string emptyPath = string.Empty; + + // Act + bool result = _sut.Exists(emptyPath); + + // Assert + result.Should().BeFalse(); + _mockPathStrategy.DidNotReceive().Exists(Arg.Any()); + } + + [Fact] + public void Exists_WithNullPath_ShouldReturnFalse() + { + // Arrange + string? nullPath = null; + + // Act + bool result = _sut.Exists(nullPath!); + + // Assert + result.Should().BeFalse(); + _mockPathStrategy.DidNotReceive().Exists(Arg.Any()); + } + + [Fact] + public void CombinePath_WithValidPathAndName_ShouldReturnCombinedPath() + { + // Arrange + string path = @"C:\BaseDir"; + string name = "SubDir"; + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); + FileSystemPathId combinedPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\BaseDir\SubDir"); + _mockPathStrategy.CombinePath(pathId, name).Returns(ErrorOrFactory.From(combinedPathId)); + + // Act + ErrorOr result = _sut.CombinePath(path, name); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().Be(@"C:\BaseDir\SubDir"); + _mockPathStrategy.Received(1).CombinePath(Arg.Is(id => id.Path == path), name); + } + + [Fact] + public void CombinePath_WithInvalidPath_ShouldReturnError() + { + // Arrange + string invalidPath = string.Empty; + string name = "SubDir"; + + // Act + ErrorOr result = _sut.CombinePath(invalidPath, name); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + _mockPathStrategy.DidNotReceive().CombinePath(Arg.Any(), Arg.Any()); + } + + [Fact] + public void CombinePath_WhenPathStrategyReturnsError_ShouldPropagateError() + { + // Arrange + string path = @"C:\BaseDir"; + string name = "Invalid*Name"; + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); + _mockPathStrategy.CombinePath(pathId, name).Returns(Errors.FileManagement.InvalidPath); + + // Act + ErrorOr result = _sut.CombinePath(path, name); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + _mockPathStrategy.Received(1).CombinePath(Arg.Is(id => id.Path == path), name); + } + + [Fact] + public void CombinePath_WithNullName_ShouldReturnError() + { + // Arrange + string path = @"C:\BaseDir"; + string? name = null; + + // Act + ErrorOr result = _sut.CombinePath(path, name!); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + _mockPathStrategy.DidNotReceive().CombinePath(Arg.Any(), Arg.Any()); + } + + [Fact] + public void ParsePath_WithValidPath_ShouldReturnPathSegments() + { + // Arrange + string validPath = @"C:\ValidPath\SubDir"; + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(validPath); + List expectedSegments = _pathSegmentFixture.CreateMany(); + _mockPathStrategy.ParsePath(pathId).Returns(ErrorOrFactory.From(expectedSegments.AsEnumerable())); + + // Act + ErrorOr> result = _sut.ParsePath(validPath); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().BeEquivalentTo(expectedSegments); + _mockPathStrategy.Received(1).ParsePath(Arg.Is(id => id.Path == validPath)); + } + + [Fact] + public void ParsePath_WithInvalidPath_ShouldReturnError() + { + // Arrange + string invalidPath = string.Empty; + + // Act + ErrorOr> result = _sut.ParsePath(invalidPath); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + _mockPathStrategy.DidNotReceive().ParsePath(Arg.Any()); + } + + [Fact] + public void ParsePath_WhenPathStrategyReturnsError_ShouldPropagateError() + { + // Arrange + string path = @"C:\InvalidPath\*SubDir"; + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); + _mockPathStrategy.ParsePath(pathId).Returns(Errors.FileManagement.InvalidPath); + + // Act + ErrorOr> result = _sut.ParsePath(path); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + _mockPathStrategy.Received(1).ParsePath(Arg.Is(id => id.Path == path)); + } + + [Fact] + public void ParsePath_WithNullPath_ShouldReturnError() + { + // Arrange + string? nullPath = null; + + // Act + ErrorOr> result = _sut.ParsePath(nullPath!); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + _mockPathStrategy.DidNotReceive().ParsePath(Arg.Any()); + } + + [Fact] + public void GoUpOneLevel_WithValidPath_ShouldReturnParentPathSegments() + { + // Arrange + string validPath = @"C:\ValidPath\SubDir"; + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(validPath); + List expectedSegments = _pathSegmentFixture.CreateMany(2); // Assuming parent path has 2 segments + _mockPathStrategy.GoUpOneLevel(pathId).Returns(ErrorOrFactory.From(expectedSegments.AsEnumerable())); + + // Act + ErrorOr> result = _sut.GoUpOneLevel(validPath); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().BeEquivalentTo(expectedSegments); + _mockPathStrategy.Received(1).GoUpOneLevel(Arg.Is(id => id.Path == validPath)); + } + + [Fact] + public void GoUpOneLevel_WithRootPath_ShouldReturnEmptySegmentList() + { + // Arrange + string rootPath = @"C:\"; + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(rootPath); + List emptySegmentList = []; + _mockPathStrategy.GoUpOneLevel(pathId).Returns(ErrorOrFactory.From(emptySegmentList.AsEnumerable())); + + // Act + ErrorOr> result = _sut.GoUpOneLevel(rootPath); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().BeEmpty(); + _mockPathStrategy.Received(1).GoUpOneLevel(Arg.Is(id => id.Path == rootPath)); + } + + [Fact] + public void GoUpOneLevel_WithInvalidPath_ShouldReturnError() + { + // Arrange + string invalidPath = string.Empty; + + // Act + ErrorOr> result = _sut.GoUpOneLevel(invalidPath); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + _mockPathStrategy.DidNotReceive().GoUpOneLevel(Arg.Any()); + } + + [Fact] + public void GoUpOneLevel_WhenPathStrategyReturnsError_ShouldPropagateError() + { + // Arrange + string path = @"C:\InvalidPath\*SubDir"; + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); + _mockPathStrategy.GoUpOneLevel(pathId).Returns(Errors.FileManagement.InvalidPath); + + // Act + ErrorOr> result = _sut.GoUpOneLevel(path); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + _mockPathStrategy.Received(1).GoUpOneLevel(Arg.Is(id => id.Path == path)); + } + + [Fact] + public void GoUpOneLevel_WithNullPath_ShouldReturnError() + { + // Arrange + string? nullPath = null; + + // Act + ErrorOr> result = _sut.GoUpOneLevel(nullPath!); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + _mockPathStrategy.DidNotReceive().GoUpOneLevel(Arg.Any()); + } + + [Fact] + public void GetInvalidPathCharsForPlatform_WhenCalled_ShouldReturnInvalidCharsFromPathStrategy() + { + // Arrange + char[] expectedInvalidChars = ['<', '>', ':', '"', '|', '?', '*']; + _mockPathStrategy.GetInvalidPathCharsForPlatform().Returns(expectedInvalidChars); + + // Act + char[] result = _sut.GetInvalidPathCharsForPlatform(); + + // Assert + result.Should().BeEquivalentTo(expectedInvalidChars); + _mockPathStrategy.Received(1).GetInvalidPathCharsForPlatform(); + } + + [Fact] + public void GetInvalidPathCharsForPlatform_WhenPathStrategyReturnsEmptyArray_ShouldReturnEmptyArray() + { + // Arrange + char[] emptyArray = []; + _mockPathStrategy.GetInvalidPathCharsForPlatform().Returns(emptyArray); + + // Act + char[] result = _sut.GetInvalidPathCharsForPlatform(); + + // Assert + result.Should().BeEmpty(); + _mockPathStrategy.Received(1).GetInvalidPathCharsForPlatform(); + } + + [Fact] + public void GetInvalidPathCharsForPlatform_WhenReturnedArrayIsModified_ShouldNotAffectSubsequentCalls() + { + // Arrange + char[] originalInvalidChars = ['<', '>', ':', '"', '|', '?', '*']; + _mockPathStrategy.GetInvalidPathCharsForPlatform().Returns(originalInvalidChars); + + // Act + char[] result = _sut.GetInvalidPathCharsForPlatform(); + result[0] = 'X'; // Attempt to modify the returned array + + // Assert + char[] secondResult = _sut.GetInvalidPathCharsForPlatform(); + secondResult.Should().BeEquivalentTo(originalInvalidChars); + _mockPathStrategy.Received(2).GetInvalidPathCharsForPlatform(); + } + + [Fact] + public void GetPathRoot_WhenCalledWithValidPath_ShouldReturnRootPathSegment() + { + // Arrange + string validPath = @"C:\ValidPath\SubDir"; + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(validPath); + PathSegment expectedRootSegment = _pathSegmentFixture.CreatePathSegment(name: "C:", isDirectory: false, isDrive: true); + _mockPathStrategy.GetPathRoot(pathId).Returns(ErrorOrFactory.From(expectedRootSegment)); + + // Act + ErrorOr result = _sut.GetPathRoot(validPath); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().BeEquivalentTo(expectedRootSegment); + _mockPathStrategy.Received(1).GetPathRoot(Arg.Is(id => id.Path == validPath)); + } + + [Fact] + public void GetPathRoot_WhenCalledWithInvalidPath_ShouldReturnError() + { + // Arrange + string invalidPath = string.Empty; + + // Act + ErrorOr result = _sut.GetPathRoot(invalidPath); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + _mockPathStrategy.DidNotReceive().GetPathRoot(Arg.Any()); + } + + [Fact] + public void GetPathRoot_WhenPathStrategyReturnsError_ShouldPropagateError() + { + // Arrange + string path = @"C:\InvalidPath\*SubDir"; + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); + _mockPathStrategy.GetPathRoot(pathId).Returns(Errors.FileManagement.InvalidPath); + + // Act + ErrorOr result = _sut.GetPathRoot(path); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + _mockPathStrategy.Received(1).GetPathRoot(Arg.Is(id => id.Path == path)); + } + + [Fact] + public void GetPathRoot_WhenCalledWithNullPath_ShouldReturnError() + { + // Arrange + string? nullPath = null; + + // Act + ErrorOr result = _sut.GetPathRoot(nullPath!); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + _mockPathStrategy.DidNotReceive().GetPathRoot(Arg.Any()); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Services/ThumbnailServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Services/ThumbnailServiceTests.cs new file mode 100644 index 00000000..37ccc078 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Services/ThumbnailServiceTests.cs @@ -0,0 +1,195 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FluentAssertions; +using Lumina.Contracts.Enums.PhotoLibrary; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Environment; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Services.Fixtures; +using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects.Fixtures; +using NSubstitute; +using SixLabors.ImageSharp; +using SixLabors.ImageSharp.Formats.Jpeg; +using SixLabors.ImageSharp.PixelFormats; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Services; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ThumbnailServiceTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly IEnvironmentContext _mockEnvironmentContext; + private readonly ThumbnailService _sut; + private readonly FileSystemPathIdFixture _fileSystemPathIdFixture; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public ThumbnailServiceTests() + { + _mockEnvironmentContext = Substitute.For(); + _sut = new ThumbnailService(_mockEnvironmentContext); + _fileSystemPathIdFixture = new FileSystemPathIdFixture(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public async Task GetThumbnailAsync_WithValidPath_ShouldReturnThumbnail() + { + // Arrange + string path = @"C:\TestImage.jpg"; + int quality = 80; + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); + + // Create a small valid JPEG image + byte[] imageBytes; + using (Image image = new(10, 10)) + { + using MemoryStream ms = new(); + image.Save(ms, new JpegEncoder()); + imageBytes = ms.ToArray(); + } + + _mockEnvironmentContext.FileTypeService.GetImageTypeAsync(pathId, Arg.Any()) + .Returns(ErrorOrFactory.From(ImageType.JPEG)); + _mockEnvironmentContext.FileProviderService.GetFileAsync(pathId) + .Returns(ErrorOrFactory.From(imageBytes)); + + // Act + ErrorOr result = await _sut.GetThumbnailAsync(path, quality, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Type.Should().Be(ImageType.JPEG); + result.Value.Bytes.Should().NotBeEmpty(); + } + + [Fact] + public async Task GetThumbnailAsync_WithInvalidPath_ShouldReturnError() + { + // Arrange + string invalidPath = string.Empty; + int quality = 80; + + // Act + ErrorOr result = await _sut.GetThumbnailAsync(invalidPath, quality, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + } + + [Fact] + public async Task GetThumbnailAsync_WhenFileTypeServiceReturnsError_ShouldPropagateError() + { + // Arrange + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestImage.jpg"); + int quality = 80; + + _mockEnvironmentContext.FileTypeService.GetImageTypeAsync(pathId, Arg.Any()) + .Returns(Errors.Permission.UnauthorizedAccess); + + // Act + ErrorOr result = await _sut.GetThumbnailAsync(pathId, quality, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess); + } + + [Fact] + public async Task GetThumbnailAsync_WhenImageTypeIsNone_ShouldReturnNoThumbnailError() + { + // Arrange + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestFile.txt"); + int quality = 80; + + _mockEnvironmentContext.FileTypeService.GetImageTypeAsync(pathId, Arg.Any()) + .Returns(ErrorOrFactory.From(ImageType.None)); + + // Act + ErrorOr result = await _sut.GetThumbnailAsync(pathId, quality, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Thumbnails.NoThumbnail); + } + + [Fact] + public async Task GetThumbnailAsync_WhenFileProviderServiceReturnsError_ShouldPropagateError() + { + // Arrange + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestImage.jpg"); + int quality = 80; + + _mockEnvironmentContext.FileTypeService.GetImageTypeAsync(pathId, Arg.Any()) + .Returns(ErrorOrFactory.From(ImageType.JPEG)); + _mockEnvironmentContext.FileProviderService.GetFileAsync(pathId) + .Returns(Errors.Permission.UnauthorizedAccess); + + // Act + ErrorOr result = await _sut.GetThumbnailAsync(pathId, quality, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess); + } + + [Theory] + [ClassData(typeof(ImageTypeFixture))] + public async Task GetThumbnailAsync_WithDifferentImageTypes_ShouldReturnThumbnail(ImageType imageType, byte[] imageBytes) + { + // Arrange + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestImage"); + int quality = 80; + + _mockEnvironmentContext.FileTypeService.GetImageTypeAsync(pathId, Arg.Any()) + .Returns(ErrorOrFactory.From(imageType)); + _mockEnvironmentContext.FileProviderService.GetFileAsync(pathId) + .Returns(ErrorOrFactory.From(imageBytes)); + + // Act + ErrorOr result = await _sut.GetThumbnailAsync(pathId, quality, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Type.Should().Be(imageType); + result.Value.Bytes.Should().NotBeEmpty(); + + using (MemoryStream ms = new(result.Value.Bytes)) + { + Image loadedImage = Image.Load(ms); + loadedImage.Should().NotBeNull(); + } + } + + [Fact] + public async Task GetThumbnailAsync_WithCancellation_ShouldThrowTaskCanceledException() + { + // Arrange + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestImage.jpg"); + int quality = 80; + CancellationTokenSource cts = new(); + cts.Cancel(); + + _mockEnvironmentContext.FileTypeService.GetImageTypeAsync(pathId, cts.Token) + .Returns(Task.FromCanceled>(cts.Token)); + + // Act & Assert + await Assert.ThrowsAsync(() => + _sut.GetThumbnailAsync(pathId, quality, cts.Token)); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Strategies/Environment/EnvironmentContextTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Strategies/Environment/EnvironmentContextTests.cs new file mode 100644 index 00000000..5f30494c --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Strategies/Environment/EnvironmentContextTests.cs @@ -0,0 +1,99 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Environment; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Strategies.Environment; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class EnvironmentContextTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly IDirectoryProviderService _mockDirectoryProviderService; + private readonly IFileProviderService _mockFileProviderService; + private readonly IFileTypeService _mockFileTypeService; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public EnvironmentContextTests() + { + _mockDirectoryProviderService = Substitute.For(); + _mockFileProviderService = Substitute.For(); + _mockFileTypeService = Substitute.For(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public void Constructor_WhenCalledWithValidParameters_ShouldInitializeAllProperties() + { + // Arrange & Act + EnvironmentContext environmentContext = new( + _mockDirectoryProviderService, + _mockFileProviderService, + _mockFileTypeService); + + // Assert + environmentContext.DirectoryProviderService.Should().Be(_mockDirectoryProviderService); + environmentContext.FileProviderService.Should().Be(_mockFileProviderService); + environmentContext.FileTypeService.Should().Be(_mockFileTypeService); + } + + [Fact] + public void FileTypeService_WhenAccessed_ShouldReturnInjectedService() + { + // Arrange + EnvironmentContext environmentContext = new( + _mockDirectoryProviderService, + _mockFileProviderService, + _mockFileTypeService); + + // Act + IFileTypeService result = environmentContext.FileTypeService; + + // Assert + result.Should().Be(_mockFileTypeService); + } + + [Fact] + public void FileProviderService_WhenAccessed_ShouldReturnInjectedService() + { + // Arrange + EnvironmentContext environmentContext = new( + _mockDirectoryProviderService, + _mockFileProviderService, + _mockFileTypeService); + + // Act + IFileProviderService result = environmentContext.FileProviderService; + + // Assert + result.Should().Be(_mockFileProviderService); + } + + [Fact] + public void DirectoryProviderService_WhenAccessed_ShouldReturnInjectedService() + { + // Arrange + EnvironmentContext environmentContext = new( + _mockDirectoryProviderService, + _mockFileProviderService, + _mockFileTypeService); + + // Act + IDirectoryProviderService result = environmentContext.DirectoryProviderService; + + // Assert + result.Should().Be(_mockDirectoryProviderService); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Strategies/Path/UnixPathStrategyTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Strategies/Path/UnixPathStrategyTests.cs new file mode 100644 index 00000000..7b4b1276 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Strategies/Path/UnixPathStrategyTests.cs @@ -0,0 +1,536 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FluentAssertions; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Path; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects.Fixtures; +using NSubstitute; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO.Abstractions; +using System.Linq; +#endregion + +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Strategies.Path; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UnixPathStrategyTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly IFileSystem _mockFileSystem; + private readonly UnixPathStrategy _sut; + private readonly FileSystemPathIdFixture _fileSystemPathIdFixture; + private readonly PathSegmentFixture _pathSegmentFixture; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public UnixPathStrategyTests() + { + _mockFileSystem = Substitute.For(); + _sut = new UnixPathStrategy(_mockFileSystem); + _fileSystemPathIdFixture = new FileSystemPathIdFixture(); + _pathSegmentFixture = new PathSegmentFixture(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Theory] + [InlineData("/home/user")] + [InlineData("/var/log/")] + [InlineData("/etc/config.conf")] + [InlineData("/")] + [InlineData("/usr/local/bin")] + public void IsValidPath_WithValidUnixPaths_ShouldReturnTrue(string path) + { + // Arrange + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); + + // Act + bool result = _sut.IsValidPath(pathId); + + // Assert + result.Should().BeTrue(); + } + + [Theory] + [InlineData("C:\\Windows\\System32")] + [InlineData("relative/path")] + [InlineData("./relative/path")] + [InlineData("../parent/path")] + public void IsValidPath_WithInvalidUnixPaths_ShouldReturnFalse(string path) + { + // Arrange + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); + + // Act + bool result = _sut.IsValidPath(pathId); + + // Assert + result.Should().BeFalse(); + } + + [Fact] + public void IsValidPath_WithPathContainingInvalidCharacters_ShouldReturnFalse() + { + // Arrange + string invalidPath = "/home/user/file\0name"; + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(invalidPath); + + // Act + bool result = _sut.IsValidPath(pathId); + + // Assert + result.Should().BeFalse(); + } + + [Theory] + [InlineData("/home/user/file with spaces")] + [InlineData("/home/user/file-with-dashes")] + [InlineData("/home/user/file_with_underscores")] + [InlineData("/home/user/file.with.dots")] + [InlineData("/home/user/file~with~tilde")] + [InlineData("/home/user/file!with!exclamation")] + [InlineData("/home/user/file$with$dollar")] + [InlineData("/home/user/file&with&ersand")] + [InlineData("/home/user/file'with'singlequote")] + [InlineData("/home/user/file(with)parentheses")] + public void IsValidPath_WithValidSpecialCharacters_ShouldReturnTrue(string path) + { + // Arrange + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); + + // Act + bool result = _sut.IsValidPath(pathId); + + // Assert + result.Should().BeTrue(); + } + + [Fact] + public void IsValidPath_WithVeryLongPath_ShouldReturnTrue() + { + // Arrange + string longPath = "/" + string.Join("/", Enumerable.Repeat("a", 100)); + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(longPath); + + // Act + bool result = _sut.IsValidPath(pathId); + + // Assert + result.Should().BeTrue(); + } + + [Fact] + public void Exists_WhenPathExists_ShouldReturnTrue() + { + // Arrange + string existingPath = "/home/user/existing_file.txt"; + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(existingPath); + _mockFileSystem.Path.Exists(existingPath).Returns(true); + + // Act + bool result = _sut.Exists(pathId); + + // Assert + result.Should().BeTrue(); + _mockFileSystem.Path.Received(1).Exists(existingPath); + } + + [Fact] + public void Exists_WhenPathDoesNotExist_ShouldReturnFalse() + { + // Arrange + string nonExistingPath = "/home/user/non_existing_file.txt"; + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(nonExistingPath); + _mockFileSystem.Path.Exists(nonExistingPath).Returns(false); + + // Act + bool result = _sut.Exists(pathId); + + // Assert + result.Should().BeFalse(); + _mockFileSystem.Path.Received(1).Exists(nonExistingPath); + } + + [Fact] + public void Exists_WithRootPath_ShouldCheckExistence() + { + // Arrange + string rootPath = "/"; + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(rootPath); + _mockFileSystem.Path.Exists(rootPath).Returns(true); + + // Act + bool result = _sut.Exists(pathId); + + // Assert + result.Should().BeTrue(); + _mockFileSystem.Path.Received(1).Exists(rootPath); + } + + [Fact] + public void Exists_WithDirectoryPath_ShouldCheckExistence() + { + // Arrange + string directoryPath = "/home/user/documents/"; + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(directoryPath); + _mockFileSystem.Path.Exists(directoryPath).Returns(true); + + // Act + bool result = _sut.Exists(pathId); + + // Assert + result.Should().BeTrue(); + _mockFileSystem.Path.Received(1).Exists(directoryPath); + } + + [Fact] + public void Exists_WithFilePath_ShouldCheckExistence() + { + // Arrange + string filePath = "/home/user/documents/file.txt"; + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(filePath); + _mockFileSystem.Path.Exists(filePath).Returns(true); + + // Act + bool result = _sut.Exists(pathId); + + // Assert + result.Should().BeTrue(); + _mockFileSystem.Path.Received(1).Exists(filePath); + } + + [Fact] + public void CombinePath_WithValidPathAndName_ShouldReturnCombinedPath() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/home/user"); + string name = "documents"; + + // Act + ErrorOr result = _sut.CombinePath(path, name); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Path.Should().Be("/home/user/documents/"); + } + + [Fact] + public void CombinePath_WithTrailingSlashInPath_ShouldReturnCorrectlyCombinedPath() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/home/user/"); + string name = "documents"; + + // Act + ErrorOr result = _sut.CombinePath(path, name); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Path.Should().Be("/home/user/documents/"); + } + + [Fact] + public void CombinePath_WithLeadingSlashInName_ShouldReturnCorrectlyCombinedPath() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/home/user"); + string name = "/documents"; + + // Act + ErrorOr result = _sut.CombinePath(path, name); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Path.Should().Be("/home/user/documents/"); + } + + [Fact] + public void CombinePath_WithEmptyName_ShouldReturnError() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/home/user"); + string name = ""; + + // Act + ErrorOr result = _sut.CombinePath(path, name); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.NameCannotBeEmpty); + } + + [Fact] + public void CombinePath_WithNullName_ShouldReturnError() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/home/user"); + string name = null!; + + // Act + ErrorOr result = _sut.CombinePath(path, name); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.NameCannotBeEmpty); + } + + [Fact] + public void CombinePath_WithRootPath_ShouldReturnCorrectlyCombinedPath() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/"); + string name = "home"; + + // Act + ErrorOr result = _sut.CombinePath(path, name); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Path.Should().Be("/home/"); + } + + [Fact] + public void ParsePath_WithValidUnixPath_ShouldReturnCorrectPathSegments() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/home/user/documents/file.txt"); + + // Act + ErrorOr> result = _sut.ParsePath(path); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().HaveCount(5); + result.Value.ElementAt(0).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("/", false, true)); + result.Value.ElementAt(1).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("home", true, false)); + result.Value.ElementAt(2).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("user", true, false)); + result.Value.ElementAt(3).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("documents", true, false)); + result.Value.ElementAt(4).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("file.txt", false, false)); + } + + [Fact] + public void ParsePath_WithRootPath_ShouldReturnSingleRootSegment() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/"); + + // Act + ErrorOr> result = _sut.ParsePath(path); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().HaveCount(1); + result.Value.Single().Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("/", false, true)); + } + + [Fact] + public void ParsePath_WithTrailingSlash_ShouldTreatLastSegmentAsDirectory() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/home/user/documents/"); + + // Act + ErrorOr> result = _sut.ParsePath(path); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().HaveCount(4); + result.Value.Last().Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("documents", true, false)); + } + + [Fact] + public void ParsePath_WithRelativePath_ShouldReturnError() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("home/user"); + + // Act + ErrorOr> result = _sut.ParsePath(path); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + } + + [Fact] + public void ParsePath_WithPathContainingDots_ShouldParseCorrectly() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/home/user/file.with.dots.txt"); + + // Act + ErrorOr> result = _sut.ParsePath(path); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().HaveCount(4); + result.Value.Last().Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("file.with.dots.txt", false, false)); + } + + [Fact] + public void GoUpOneLevel_WithValidPath_ShouldReturnParentPath() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/home/user/documents"); + + // Act + ErrorOr> result = _sut.GoUpOneLevel(path); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().HaveCount(3); + result.Value.ElementAt(0).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("/", false, true)); + result.Value.ElementAt(1).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("home", true, false)); + result.Value.ElementAt(2).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("user", true, false)); + } + + [Fact] + public void GoUpOneLevel_WithRootPath_ShouldReturnError() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/"); + + // Act + ErrorOr> result = _sut.GoUpOneLevel(path); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.CannotNavigateUp); + } + + [Fact] + public void GoUpOneLevel_WithTrailingSlash_ShouldReturnCorrectParentPath() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/home/user/"); + + // Act + ErrorOr> result = _sut.GoUpOneLevel(path); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().HaveCount(2); + result.Value.ElementAt(0).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("/", false, true)); + result.Value.ElementAt(1).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("home", true, false)); + } + + [Fact] + public void GoUpOneLevel_WithInvalidPath_ShouldReturnError() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("invalid/path"); + + // Act + ErrorOr> result = _sut.GoUpOneLevel(path); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + } + + [Fact] + public void GoUpOneLevel_WithSingleLevelPath_ShouldReturnRootPath() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/home"); + + // Act + ErrorOr> result = _sut.GoUpOneLevel(path); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().HaveCount(1); + result.Value.Single().Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("/", false, true)); + } + + [Fact] + public void GetInvalidPathCharsForPlatform_WhenCalled_ShouldReturnOnlyNullCharacter() + { + // Act + char[] result = _sut.GetInvalidPathCharsForPlatform(); + + // Assert + result.Should().HaveCount(1); + result.Should().Contain('\0'); + } + + [Fact] + public void GetInvalidPathCharsForPlatform_WhenCalled_ShouldNotContainOtherCharacters() + { + // Act + char[] result = _sut.GetInvalidPathCharsForPlatform(); + + // Assert + result.Should().NotContain('/'); + result.Should().NotContain('\\'); + result.Should().NotContain(':'); + result.Should().NotContain('*'); + result.Should().NotContain('?'); + result.Should().NotContain('"'); + result.Should().NotContain('<'); + result.Should().NotContain('>'); + result.Should().NotContain('|'); + } + + [Fact] + public void GetInvalidPathCharsForPlatform_WhenCalled_ShouldReturnSameResultOnMultipleCalls() + { + // Act + char[] result1 = _sut.GetInvalidPathCharsForPlatform(); + char[] result2 = _sut.GetInvalidPathCharsForPlatform(); + + // Assert + result1.Should().BeEquivalentTo(result2); + } + + [Fact] + public void GetPathRoot_WithValidUnixPath_ShouldReturnRootSegment() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/home/user/documents"); + + // Act + ErrorOr result = _sut.GetPathRoot(path); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("/", false, true)); + } + + [Fact] + public void GetPathRoot_WithRootPath_ShouldReturnRootSegment() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/"); + + // Act + ErrorOr result = _sut.GetPathRoot(path); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("/", false, true)); + } + + [Fact] + public void GetPathRoot_WithInvalidPath_ShouldReturnError() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("home/user"); + + // Act + ErrorOr result = _sut.GetPathRoot(path); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Strategies/Path/WindowsPathStrategyTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Strategies/Path/WindowsPathStrategyTests.cs new file mode 100644 index 00000000..b07b50df --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Strategies/Path/WindowsPathStrategyTests.cs @@ -0,0 +1,753 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FluentAssertions; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Path; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects.Fixtures; +using NSubstitute; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO.Abstractions; +using System.Linq; +#endregion + +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Strategies.Path; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class WindowsPathStrategyTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly IFileSystem _mockFileSystem; + private readonly WindowsPathStrategy _sut; + private readonly FileSystemPathIdFixture _fileSystemPathIdFixture; + private readonly PathSegmentFixture _pathSegmentFixture; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public WindowsPathStrategyTests() + { + _mockFileSystem = Substitute.For(); + _sut = new WindowsPathStrategy(_mockFileSystem); + _fileSystemPathIdFixture = new FileSystemPathIdFixture(); + _pathSegmentFixture = new PathSegmentFixture(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Theory] + [InlineData(@"C:\Users\User")] + [InlineData(@"D:\Program Files\")] + [InlineData(@"E:\Documents\file.txt")] + [InlineData(@"F:\")] + [InlineData(@"G:\Projects\Visual Studio 2022\")] + public void IsValidPath_WithValidWindowsPaths_ShouldReturnTrue(string path) + { + // Arrange + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); + + // Act + bool result = _sut.IsValidPath(pathId); + + // Assert + result.Should().BeTrue(); + } + + [Theory] + [InlineData("/home/user")] + [InlineData("relative\\path")] + [InlineData(".\\relative\\path")] + [InlineData("..\\parent\\path")] + [InlineData("C:invalid_path")] + public void IsValidPath_WithInvalidWindowsPaths_ShouldReturnFalse(string path) + { + // Arrange + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); + + // Act + bool result = _sut.IsValidPath(pathId); + + // Assert + result.Should().BeFalse(); + } + + [Fact] + public void IsValidPath_WithPathContainingInvalidCharacters_ShouldReturnFalse() + { + // Arrange + string invalidPath = @"C:\Users\User\file"; + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(invalidPath); + + // Act + bool result = _sut.IsValidPath(pathId); + + // Assert + result.Should().BeFalse(); + } + + [Theory] + [InlineData(@"C:\Users\User\file with spaces")] + [InlineData(@"D:\Projects\file-with-dashes")] + [InlineData(@"E:\Documents\file_with_underscores")] + [InlineData(@"F:\Data\file.with.dots")] + [InlineData(@"G:\Backups\file(with)parentheses")] + public void IsValidPath_WithValidSpecialCharacters_ShouldReturnTrue(string path) + { + // Arrange + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); + + // Act + bool result = _sut.IsValidPath(pathId); + + // Assert + result.Should().BeTrue(); + } + + [Fact] + public void IsValidPath_WithVeryLongPath_ShouldReturnTrue() + { + // Arrange + string longPath = @"C:\" + string.Join("\\", Enumerable.Repeat("a", 100)); + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(longPath); + + // Act + bool result = _sut.IsValidPath(pathId); + + // Assert + result.Should().BeTrue(); + } + + [Theory] + [InlineData(@"\\server\share")] + [InlineData(@"\\server\share\folder")] + [InlineData(@"\\server\share\folder\file.txt")] + public void IsValidPath_WithValidUNCPaths_ShouldReturnTrue(string path) + { + // Arrange + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); + + // Act + bool result = _sut.IsValidPath(pathId); + + // Assert + result.Should().BeTrue(); + } + + [Theory] + [InlineData(@"\\")] + [InlineData(@"\\server")] + [InlineData(@"\\\server\share")] + public void IsValidPath_WithInvalidUNCPaths_ShouldReturnFalse(string path) + { + // Arrange + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path); + + // Act + bool result = _sut.IsValidPath(pathId); + + // Assert + result.Should().BeFalse(); + } + + [Fact] + public void Exists_WhenPathExists_ShouldReturnTrue() + { + // Arrange + string existingPath = @"C:\Users\User\existing_file.txt"; + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(existingPath); + _mockFileSystem.Path.Exists(existingPath).Returns(true); + + // Act + bool result = _sut.Exists(pathId); + + // Assert + result.Should().BeTrue(); + _mockFileSystem.Path.Received(1).Exists(existingPath); + } + + [Fact] + public void Exists_WhenPathDoesNotExist_ShouldReturnFalse() + { + // Arrange + string nonExistingPath = @"C:\Users\User\non_existing_file.txt"; + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(nonExistingPath); + _mockFileSystem.Path.Exists(nonExistingPath).Returns(false); + + // Act + bool result = _sut.Exists(pathId); + + // Assert + result.Should().BeFalse(); + _mockFileSystem.Path.Received(1).Exists(nonExistingPath); + } + + [Fact] + public void Exists_WithRootPath_ShouldCheckExistence() + { + // Arrange + string rootPath = @"C:\"; + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(rootPath); + _mockFileSystem.Path.Exists(rootPath).Returns(true); + + // Act + bool result = _sut.Exists(pathId); + + // Assert + result.Should().BeTrue(); + _mockFileSystem.Path.Received(1).Exists(rootPath); + } + + [Fact] + public void Exists_WithDirectoryPath_ShouldCheckExistence() + { + // Arrange + string directoryPath = @"C:\Users\User\Documents\"; + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(directoryPath); + _mockFileSystem.Path.Exists(directoryPath).Returns(true); + + // Act + bool result = _sut.Exists(pathId); + + // Assert + result.Should().BeTrue(); + _mockFileSystem.Path.Received(1).Exists(directoryPath); + } + + [Fact] + public void Exists_WithFilePath_ShouldCheckExistence() + { + // Arrange + string filePath = @"C:\Users\User\Documents\file.txt"; + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(filePath); + _mockFileSystem.Path.Exists(filePath).Returns(true); + + // Act + bool result = _sut.Exists(pathId); + + // Assert + result.Should().BeTrue(); + _mockFileSystem.Path.Received(1).Exists(filePath); + } + + [Fact] + public void Exists_WithUNCPath_ShouldCheckExistence() + { + // Arrange + string uncPath = @"\\server\share\folder\file.txt"; + FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(uncPath); + _mockFileSystem.Path.Exists(uncPath).Returns(true); + + // Act + bool result = _sut.Exists(pathId); + + // Assert + result.Should().BeTrue(); + _mockFileSystem.Path.Received(1).Exists(uncPath); + } + + [Fact] + public void CombinePath_WithValidPathAndName_ShouldReturnCombinedPath() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Users\User"); + string name = "Documents"; + + // Act + ErrorOr result = _sut.CombinePath(path, name); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Path.Should().Be(@"C:\Users\User\Documents\"); + } + + [Fact] + public void CombinePath_WithTrailingBackslashInPath_ShouldReturnCorrectlyCombinedPath() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Users\User\"); + string name = "Documents"; + + // Act + ErrorOr result = _sut.CombinePath(path, name); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Path.Should().Be(@"C:\Users\User\Documents\"); + } + + [Fact] + public void CombinePath_WithLeadingBackslashInName_ShouldReturnCorrectlyCombinedPath() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Users\User"); + string name = @"\Documents"; + + // Act + ErrorOr result = _sut.CombinePath(path, name); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Path.Should().Be(@"C:\Users\User\Documents\"); + } + + [Fact] + public void CombinePath_WithNullName_ShouldReturnError() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Users\User"); + string name = null!; + + // Act + ErrorOr result = _sut.CombinePath(path, name); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.NameCannotBeEmpty); + } + + [Fact] + public void CombinePath_WithRootPath_ShouldReturnCorrectlyCombinedPath() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\"); + string name = "Users"; + + // Act + ErrorOr result = _sut.CombinePath(path, name); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Path.Should().Be(@"C:\Users\"); + } + + [Fact] + public void CombinePath_WithUNCPath_ShouldReturnCorrectlyCombinedPath() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"\\server\share"); + string name = "folder"; + + // Act + ErrorOr result = _sut.CombinePath(path, name); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Path.Should().Be(@"\\server\share\folder\"); + } + + [Fact] + public void ParsePath_WithValidWindowsPath_ShouldReturnCorrectPathSegments() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Users\User\Documents\file.txt"); + + // Act + ErrorOr> result = _sut.ParsePath(path); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().HaveCount(5); + result.Value.ElementAt(0).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("C:", false, true)); + result.Value.ElementAt(1).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("Users", true, false)); + result.Value.ElementAt(2).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("User", true, false)); + result.Value.ElementAt(3).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("Documents", true, false)); + result.Value.ElementAt(4).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("file.txt", false, false)); + } + + [Fact] + public void ParsePath_WithRootPath_ShouldReturnSingleRootSegment() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\"); + + // Act + ErrorOr> result = _sut.ParsePath(path); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().HaveCount(1); + result.Value.Single().Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("C:", false, true)); + } + + [Fact] + public void ParsePath_WithTrailingBackslash_ShouldTreatLastSegmentAsDirectory() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Users\User\Documents\"); + + // Act + ErrorOr> result = _sut.ParsePath(path); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().HaveCount(4); + result.Value.Last().Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("Documents", true, false)); + } + + [Fact] + public void ParsePath_WithRelativePath_ShouldReturnError() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"Users\User"); + + // Act + ErrorOr> result = _sut.ParsePath(path); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + } + + [Fact] + public void ParsePath_WithPathContainingDots_ShouldParseCorrectly() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Users\User\file.with.dots.txt"); + + // Act + ErrorOr> result = _sut.ParsePath(path); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().HaveCount(4); + result.Value.Last().Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("file.with.dots.txt", false, false)); + } + + [Fact] + public void ParsePath_WithUNCPath_ShouldReturnCorrectPathSegments() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"\\server\share\folder\file.txt"); + + // Act + ErrorOr> result = _sut.ParsePath(path); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().HaveCount(5); + result.Value.ElementAt(0).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment(@"\\", false, true)); + result.Value.ElementAt(1).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("server", true, false)); + result.Value.ElementAt(2).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("share", true, false)); + result.Value.ElementAt(3).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("folder", true, false)); + result.Value.ElementAt(4).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("file.txt", false, false)); + } + + [Fact] + public void GoUpOneLevel_WithValidPath_ShouldReturnParentPath() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Users\User\Documents"); + + // Act + ErrorOr> result = _sut.GoUpOneLevel(path); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().HaveCount(3); + result.Value.ElementAt(0).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("C:", false, true)); + result.Value.ElementAt(1).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("Users", true, false)); + result.Value.ElementAt(2).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("User", true, false)); + } + + [Fact] + public void GoUpOneLevel_WithRootPath_ShouldReturnError() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\"); + + // Act + ErrorOr> result = _sut.GoUpOneLevel(path); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.CannotNavigateUp); + } + + [Fact] + public void GoUpOneLevel_WithTrailingBackslash_ShouldReturnCorrectParentPath() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Users\User\"); + + // Act + ErrorOr> result = _sut.GoUpOneLevel(path); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().HaveCount(2); + result.Value.ElementAt(0).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("C:", false, true)); + result.Value.ElementAt(1).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("Users", true, false)); + } + + [Fact] + public void GoUpOneLevel_WithInvalidPath_ShouldReturnError() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"invalid\path"); + + // Act + ErrorOr> result = _sut.GoUpOneLevel(path); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + } + + [Fact] + public void GoUpOneLevel_WithSingleLevelPath_ShouldReturnRootPath() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Users"); + + // Act + ErrorOr> result = _sut.GoUpOneLevel(path); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().HaveCount(1); + result.Value.Single().Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("C:", false, true)); + } + + [Fact] + public void GoUpOneLevel_WithUNCPath_ShouldReturnParentPath() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"\\server\share\folder\subfolder"); + + // Act + ErrorOr> result = _sut.GoUpOneLevel(path); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().HaveCount(4); + result.Value.ElementAt(0).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment(@"\\", false, true)); + result.Value.ElementAt(1).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("server", true, false)); + result.Value.ElementAt(2).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("share", true, false)); + result.Value.ElementAt(3).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("folder", true, false)); + } + + [Fact] + public void GoUpOneLevel_WithUNCRootPath_ShouldReturnError() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"\\server\share"); + + // Act + ErrorOr> result = _sut.GoUpOneLevel(path); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.CannotNavigateUp); + } + + [Fact] + public void GoUpOneLevel_WithUNCPathWithOneFolder_ShouldReturnUNCRoot() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"\\server\share\folder"); + + // Act + ErrorOr> result = _sut.GoUpOneLevel(path); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().HaveCount(3); + result.Value.ElementAt(0).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment(@"\\", false, true)); + result.Value.ElementAt(1).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("server", true, false)); + result.Value.ElementAt(2).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("share", true, false)); + } + + [Fact] + public void GoUpOneLevel_WithDriveRootAndBackslash_ShouldReturnError() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\"); + + // Act + ErrorOr> result = _sut.GoUpOneLevel(path); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.CannotNavigateUp); + } + + [Fact] + public void GetInvalidPathCharsForPlatform_WhenCalled_ShouldReturnExpectedCharacters() + { + // Act + char[] result = _sut.GetInvalidPathCharsForPlatform(); + + // Assert + result.Should().BeEquivalentTo(['<', '>', '"', '/', '|', '?', '*' ]); + } + + [Fact] + public void GetInvalidPathCharsForPlatform_WhenCalled_ShouldNotContainCertainCharacters() + { + // Act + char[] result = _sut.GetInvalidPathCharsForPlatform(); + + // Assert + result.Should().NotContain('\\'); + result.Should().NotContain(':'); + result.Should().NotContain('\0'); + } + + [Fact] + public void GetInvalidPathCharsForPlatform_WhenCalled_ShouldReturnSameResultOnMultipleCalls() + { + // Act + char[] result1 = _sut.GetInvalidPathCharsForPlatform(); + char[] result2 = _sut.GetInvalidPathCharsForPlatform(); + + // Assert + result1.Should().BeEquivalentTo(result2); + } + + [Fact] + public void GetPathRoot_WithValidWindowsPath_ShouldReturnRootSegment() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Users\User\Documents"); + + // Act + ErrorOr result = _sut.GetPathRoot(path); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("C:\\", true, true)); + } + + [Fact] + public void GetPathRoot_WithRootPath_ShouldReturnRootSegment() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\"); + + // Act + ErrorOr result = _sut.GetPathRoot(path); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("C:\\", true, true)); + } + + [Fact] + public void GetPathRoot_WithInvalidPath_ShouldReturnError() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"InvalidFolder"); + + // Act + ErrorOr result = _sut.GetPathRoot(path); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + } + + [Fact] + public void GetPathRoot_WithUNCPath_ShouldReturnUNCRootSegment() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"\\server\share\folder"); + + // Act + ErrorOr result = _sut.GetPathRoot(path); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment(@"\\server\share\", true, false)); + } + + [Fact] + public void GetPathRoot_WithInvalidUNCPath_ShouldReturnError() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"\\"); + + // Act + ErrorOr result = _sut.GetPathRoot(path); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + } + + [Fact] + public void GetPathRoot_WithUNCPathWithoutShare_ShouldReturnError() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"\\server"); + + // Act + ErrorOr result = _sut.GetPathRoot(path); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + } + + [Fact] + public void GetPathRoot_WithNonDriveNonUNCPath_ShouldReturnError() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"InvalidPath"); + + // Act + ErrorOr result = _sut.GetPathRoot(path); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + } + + [Fact] + public void GetPathRoot_WithUNCPathMissingServerName_ShouldReturnError() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"\\"); + + // Act + ErrorOr result = _sut.GetPathRoot(path); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + } + + [Fact] + public void GetPathRoot_WithUNCPathWithoutThirdBackslash_ShouldReturnServerAndShare() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"\\server\share"); + + // Act + ErrorOr result = _sut.GetPathRoot(path); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment(@"\\server\share\", true, false)); + } + + [Fact] + public void GetPathRoot_WithNeitherUNCNorDrivePath_ShouldReturnError() + { + // Arrange + FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"invalid\path"); + + // Act + ErrorOr result = _sut.GetPathRoot(path); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Strategies/Platform/Fixtures/INonExistentPlatformContextFixture.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Strategies/Platform/Fixtures/INonExistentPlatformContextFixture.cs new file mode 100644 index 00000000..33106e51 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Strategies/Platform/Fixtures/INonExistentPlatformContextFixture.cs @@ -0,0 +1,12 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; +#endregion + +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Strategies.Platform.Fixtures; + +/// +/// Fixture interface for non existing platform context. +/// +public interface INonExistentPlatformContextFixture : IPlatformContext +{ +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Strategies/Platform/PlatformContextFactoryTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Strategies/Platform/PlatformContextFactoryTests.cs new file mode 100644 index 00000000..a86d3127 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Strategies/Platform/PlatformContextFactoryTests.cs @@ -0,0 +1,72 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Path; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; +using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Strategies.Platform.Fixtures; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO.Abstractions; +#endregion + +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Strategies.Platform; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class PlatformContextFactoryTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly IServiceProvider _serviceProvider; + private readonly PlatformContextFactory _sut; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public PlatformContextFactoryTests() + { + ServiceCollection services = new(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + _serviceProvider = services.BuildServiceProvider(); + _sut = new PlatformContextFactory(_serviceProvider); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public void CreateStrategy_WhenWindowsServiceExists_ShouldReturnWindowsService() + { + // Act + IWindowsPlatformContext result = _sut.CreateStrategy(); + + // Assert + result.Should().NotBeNull(); + result.Should().BeOfType(); + } + + [Fact] + public void CreateStrategy_WhenUnixServiceExists_ShouldReturnUnixService() + { + // Act + IUnixPlatformContext result = _sut.CreateStrategy(); + + // Assert + result.Should().NotBeNull(); + result.Should().BeOfType(); + } + + [Fact] + public void CreateStrategy_WhenServiceDoesNotExist_ShouldThrowInvalidOperationException() + { + // Act & Assert + Assert.Throws(() => _sut.CreateStrategy()); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Strategies/Platform/PlatformContextManagerTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Strategies/Platform/PlatformContextManagerTests.cs new file mode 100644 index 00000000..d2a690f9 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Strategies/Platform/PlatformContextManagerTests.cs @@ -0,0 +1,159 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Contracts.Enums.FileSystem; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.InteropServices; +#endregion + +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Strategies.Platform; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class PlatformContextManagerTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly IPlatformContextFactory _mockPlatformContextFactory; + private PlatformContextManager? sut; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public PlatformContextManagerTests() + { + _mockPlatformContextFactory = Substitute.For(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public void GetCurrentContext_WhenNoContextSet_ShouldSetDefaultContext() + { + // Arrange + IWindowsPlatformContext mockWindowsContext = Substitute.For(); + _mockPlatformContextFactory.CreateStrategy().Returns(mockWindowsContext); + IOperatingSystemInfo mockOsInfo = Substitute.For(); + mockOsInfo.IsOSPlatform(OSPlatform.Linux).Returns(false); + sut = new(_mockPlatformContextFactory, mockOsInfo); + + // Act + IPlatformContext result = sut.GetCurrentContext(); + + // Assert + result.Should().Be(mockWindowsContext); + _mockPlatformContextFactory.Received(1).CreateStrategy(); + } + + [Fact] + public void GetCurrentContext_WhenContextAlreadySet_ShouldReturnExistingContext() + { + // Arrange + IUnixPlatformContext mockUnixContext = Substitute.For(); + _mockPlatformContextFactory.CreateStrategy().Returns(mockUnixContext); + IOperatingSystemInfo mockOsInfo = Substitute.For(); + sut = new(_mockPlatformContextFactory, mockOsInfo); + sut.SetCurrentPlatform(PlatformType.Unix); + + // Act + IPlatformContext result = sut.GetCurrentContext(); + + // Assert + result.Should().Be(mockUnixContext); + _mockPlatformContextFactory.Received(1).CreateStrategy(); + } + + [Fact] + public void SetCurrentPlatform_WhenUnixPlatform_ShouldSetUnixContext() + { + // Arrange + IUnixPlatformContext mockUnixContext = Substitute.For(); + _mockPlatformContextFactory.CreateStrategy().Returns(mockUnixContext); + IOperatingSystemInfo mockOsInfo = Substitute.For(); + mockOsInfo.IsOSPlatform(OSPlatform.Linux).Returns(true); + sut = new(_mockPlatformContextFactory, mockOsInfo); + + // Act + sut.SetCurrentPlatform(PlatformType.Unix); + IPlatformContext result = sut.GetCurrentContext(); + + // Assert + result.Should().Be(mockUnixContext); + _mockPlatformContextFactory.Received(1).CreateStrategy(); + } + + [Fact] + public void SetCurrentPlatform_WhenWindowsPlatform_ShouldSetWindowsContext() + { + // Arrange + IWindowsPlatformContext mockWindowsContext = Substitute.For(); + _mockPlatformContextFactory.CreateStrategy().Returns(mockWindowsContext); + IOperatingSystemInfo mockOsInfo = Substitute.For(); + mockOsInfo.IsOSPlatform(OSPlatform.Linux).Returns(false); + sut = new(_mockPlatformContextFactory, mockOsInfo); + + // Act + sut.SetCurrentPlatform(PlatformType.Windows); + IPlatformContext result = sut.GetCurrentContext(); + + // Assert + result.Should().Be(mockWindowsContext); + _mockPlatformContextFactory.Received(1).CreateStrategy(); + } + + [Fact] + public void SetCurrentPlatform_WhenUnsupportedPlatform_ShouldThrowArgumentException() + { + // Arrange + PlatformType unsupportedPlatform = (PlatformType)999; // An unsupported platform type + IOperatingSystemInfo mockOsInfo = Substitute.For(); + sut = new(_mockPlatformContextFactory, mockOsInfo); + + // Act & Assert + Action act = () => sut.SetCurrentPlatform(unsupportedPlatform); + act.Should().Throw() + .WithMessage($"Unsupported platform type: {unsupportedPlatform}"); + } + + [Fact] + public void GetCurrentContext_WhenRunningOnLinux_ShouldSetUnixContextByDefault() + { + // Arrange + IUnixPlatformContext mockUnixContext = Substitute.For(); + _mockPlatformContextFactory.CreateStrategy().Returns(mockUnixContext); + IOperatingSystemInfo mockOsInfo = Substitute.For(); + mockOsInfo.IsOSPlatform(OSPlatform.Linux).Returns(true); + sut = new(_mockPlatformContextFactory, mockOsInfo); + + // Act + IPlatformContext result = sut.GetCurrentContext(); + + // Assert + result.Should().Be(mockUnixContext); + _mockPlatformContextFactory.Received(1).CreateStrategy(); + } + + [Fact] + public void GetCurrentContext_WhenRunningOnWindows_ShouldSetWindowsContextByDefault() + { + // Arrange + IWindowsPlatformContext mockWindowsContext = Substitute.For(); + _mockPlatformContextFactory.CreateStrategy().Returns(mockWindowsContext); + IOperatingSystemInfo mockOsInfo = Substitute.For(); + mockOsInfo.IsOSPlatform(OSPlatform.Linux).Returns(false); + sut = new(_mockPlatformContextFactory, mockOsInfo); + + // Act + IPlatformContext result = sut.GetCurrentContext(); + + // Assert + result.Should().Be(mockWindowsContext); + _mockPlatformContextFactory.Received(1).CreateStrategy(); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Strategies/Platform/PlatformContextTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Strategies/Platform/PlatformContextTests.cs new file mode 100644 index 00000000..3a33c30d --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Strategies/Platform/PlatformContextTests.cs @@ -0,0 +1,121 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Contracts.Enums.FileSystem; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Path; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Strategies.Platform; + +/// +/// Contains unit tests for the and classes. +/// +[ExcludeFromCodeCoverage] +public class PlatformContextTests +{ + #region ===================================================================== METHODS =================================================================================== + [Fact] + public void WindowsPlatformContext_Constructor_ShouldSetPropertiesCorrectly() + { + // Arrange + IWindowsPathStrategy mockWindowsPathStrategy = Substitute.For(); + + // Act + WindowsPlatformContext windowsPlatformContext = new(mockWindowsPathStrategy); + + // Assert + windowsPlatformContext.Platform.Should().Be(PlatformType.Windows); + windowsPlatformContext.PathStrategy.Should().Be(mockWindowsPathStrategy); + } + + [Fact] + public void UnixPlatformContext_Constructor_ShouldSetPropertiesCorrectly() + { + // Arrange + IUnixPathStrategy mockUnixPathStrategy = Substitute.For(); + + // Act + UnixPlatformContext unixPlatformContext = new(mockUnixPathStrategy); + + // Assert + unixPlatformContext.Platform.Should().Be(PlatformType.Unix); + unixPlatformContext.PathStrategy.Should().Be(mockUnixPathStrategy); + } + + [Fact] + public void WindowsPlatformContext_ShouldImplementIWindowsPlatformContext() + { + // Arrange + IWindowsPathStrategy mockWindowsPathStrategy = Substitute.For(); + + // Act + WindowsPlatformContext windowsPlatformContext = new(mockWindowsPathStrategy); + + // Assert + windowsPlatformContext.Should().BeAssignableTo(); + } + + [Fact] + public void UnixPlatformContext_ShouldImplementIUnixPlatformContext() + { + // Arrange + IUnixPathStrategy mockUnixPathStrategy = Substitute.For(); + + // Act + UnixPlatformContext unixPlatformContext = new(mockUnixPathStrategy); + + // Assert + unixPlatformContext.Should().BeAssignableTo(); + } + + [Fact] + public void WindowsPlatformContext_PathStrategy_ShouldBeReadOnly() + { + // Arrange + IWindowsPathStrategy mockWindowsPathStrategy = Substitute.For(); + WindowsPlatformContext windowsPlatformContext = new(mockWindowsPathStrategy); + + // Act & Assert + windowsPlatformContext.GetType().GetProperty(nameof(WindowsPlatformContext.PathStrategy))! + .SetMethod.Should().BeNull(); + } + + [Fact] + public void UnixPlatformContext_PathStrategy_ShouldBeReadOnly() + { + // Arrange + IUnixPathStrategy mockUnixPathStrategy = Substitute.For(); + UnixPlatformContext unixPlatformContext = new(mockUnixPathStrategy); + + // Act & Assert + unixPlatformContext.GetType().GetProperty(nameof(UnixPlatformContext.PathStrategy))! + .SetMethod.Should().BeNull(); + } + + [Fact] + public void WindowsPlatformContext_Platform_ShouldBeReadOnly() + { + // Arrange + IWindowsPathStrategy mockWindowsPathStrategy = Substitute.For(); + WindowsPlatformContext windowsPlatformContext = new(mockWindowsPathStrategy); + + // Act & Assert + windowsPlatformContext.GetType().GetProperty(nameof(WindowsPlatformContext.Platform))! + .SetMethod.Should().BeNull(); + } + + [Fact] + public void UnixPlatformContext_Platform_ShouldBeReadOnly() + { + // Arrange + IUnixPathStrategy mockUnixPathStrategy = Substitute.For(); + UnixPlatformContext unixPlatformContext = new(mockUnixPathStrategy); + + // Act & Assert + unixPlatformContext.GetType().GetProperty(nameof(UnixPlatformContext.Platform))! + .SetMethod.Should().BeNull(); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/ValueObjects/FileSystemPathIdTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/ValueObjects/FileSystemPathIdTests.cs new file mode 100644 index 00000000..b6e88812 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/ValueObjects/FileSystemPathIdTests.cs @@ -0,0 +1,150 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FluentAssertions; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects.Fixtures; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class FileSystemPathIdTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly FileSystemPathIdFixture _fileSystemPathIdFixture; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public FileSystemPathIdTests() + { + _fileSystemPathIdFixture = new FileSystemPathIdFixture(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public void Create_WithValidPath_ShouldReturnFileSystemPathId() + { + // Arrange + string validPath = @"C:\TestDir\file.txt"; + + // Act + ErrorOr result = FileSystemPathId.Create(validPath); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Path.Should().Be(validPath); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + public void Create_WithInvalidPath_ShouldReturnError(string invalidPath) + { + // Act + ErrorOr result = FileSystemPathId.Create(invalidPath); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.InvalidPath); + } + + [Fact] + public void Equals_WithSamePath_ShouldReturnTrue() + { + // Arrange + string path = @"C:\TestDir\file.txt"; + FileSystemPathId id1 = _fileSystemPathIdFixture.CreateFileSystemPathId(path); + FileSystemPathId id2 = _fileSystemPathIdFixture.CreateFileSystemPathId(path); + + // Act + bool result = id1.Equals(id2); + + // Assert + result.Should().BeTrue(); + } + + [Fact] + public void Equals_WithDifferentPath_ShouldReturnFalse() + { + // Arrange + FileSystemPathId id1 = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir\file1.txt"); + FileSystemPathId id2 = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir\file2.txt"); + + // Act + bool result = id1.Equals(id2); + + // Assert + result.Should().BeFalse(); + } + + [Fact] + public void GetHashCode_WithSamePath_ShouldReturnSameHashCode() + { + // Arrange + string path = @"C:\TestDir\file.txt"; + FileSystemPathId id1 = _fileSystemPathIdFixture.CreateFileSystemPathId(path); + FileSystemPathId id2 = _fileSystemPathIdFixture.CreateFileSystemPathId(path); + + // Act + int hashCode1 = id1.GetHashCode(); + int hashCode2 = id2.GetHashCode(); + + // Assert + hashCode1.Should().Be(hashCode2); + } + + [Fact] + public void GetHashCode_WithDifferentPath_ShouldReturnDifferentHashCode() + { + // Arrange + FileSystemPathId id1 = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir\file1.txt"); + FileSystemPathId id2 = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir\file2.txt"); + + // Act + int hashCode1 = id1.GetHashCode(); + int hashCode2 = id2.GetHashCode(); + + // Assert + hashCode1.Should().NotBe(hashCode2); + } + + [Fact] + public void EqualityOperator_WithSamePath_ShouldReturnTrue() + { + // Arrange + string path = @"C:\TestDir\file.txt"; + FileSystemPathId id1 = _fileSystemPathIdFixture.CreateFileSystemPathId(path); + FileSystemPathId id2 = _fileSystemPathIdFixture.CreateFileSystemPathId(path); + + // Act + bool result = id1 == id2; + + // Assert + result.Should().BeTrue(); + } + + [Fact] + public void InequalityOperator_WithDifferentPath_ShouldReturnTrue() + { + // Arrange + FileSystemPathId id1 = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir\file1.txt"); + FileSystemPathId id2 = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir\file2.txt"); + + // Act + bool result = id1 != id2; + + // Assert + result.Should().BeTrue(); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/ValueObjects/Fixtures/FileSystemPathIdFixture.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/ValueObjects/Fixtures/FileSystemPathIdFixture.cs new file mode 100644 index 00000000..93d87d02 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/ValueObjects/Fixtures/FileSystemPathIdFixture.cs @@ -0,0 +1,48 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using ErrorOr; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class FileSystemPathIdFixture +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly Faker _faker; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public FileSystemPathIdFixture() + { + _faker = new Faker(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + /// + /// Creates a random valid . + /// + /// The path of the file system path element. + /// The created . + public FileSystemPathId CreateFileSystemPathId(string? path = null) + { + path ??= _faker.System.FilePath(); + + ErrorOr fileSystemPathIdResult = FileSystemPathId.Create(path); + + if (fileSystemPathIdResult.IsError) + throw new InvalidOperationException("Failed to create FileSystemPathId: " + string.Join(", ", fileSystemPathIdResult.Errors)); + return fileSystemPathIdResult.Value; + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/ValueObjects/Fixtures/PathSegmentFixture.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/ValueObjects/Fixtures/PathSegmentFixture.cs new file mode 100644 index 00000000..59173f7e --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/ValueObjects/Fixtures/PathSegmentFixture.cs @@ -0,0 +1,64 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using ErrorOr; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class PathSegmentFixture +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly Faker _faker; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public PathSegmentFixture() + { + _faker = new Faker(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + /// + /// Creates a random valid . + /// + /// The created . + public PathSegment CreatePathSegment( + string? name = null, + bool? isDirectory = null, + bool? isDrive = null) + { + name ??= _faker.System.FileName(); + isDirectory ??= true; + isDrive ??= false; + + ErrorOr pathResult = PathSegment.Create(name, isDirectory.Value, isDrive.Value); + + if (pathResult.IsError) + throw new InvalidOperationException("Failed to create PathSegment: " + string.Join(", ", pathResult.Errors)); + return pathResult.Value; + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return Enumerable.Range(0, count).Select(_ => CreatePathSegment()).ToList(); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/ValueObjects/Fixtures/StreamInfoFixture.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/ValueObjects/Fixtures/StreamInfoFixture.cs new file mode 100644 index 00000000..fd677680 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/ValueObjects/Fixtures/StreamInfoFixture.cs @@ -0,0 +1,84 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using ErrorOr; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class StreamInfoFixture +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly Faker _faker; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public StreamInfoFixture() + { + _faker = new Faker(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + /// + /// Creates a random valid . + /// + /// Optional. The unique identifier for the stream. If not provided, a default value may be used. + /// Optional. The MIME type of the stream (e.g., video/mp4, audio/mpeg). If not provided, a default MIME type may be used. + /// Optional. The bitrate of the stream in kbps. If not provided, a default value may be used. + /// Optional. The codec used for the stream (e.g., H.264, AAC). If not provided, a default codec may be used. + /// Optional. The video resolution (e.g., 1920x1080). If not provided, a default resolution may be used. + /// Optional. The frame rate of the video stream in frames per second (fps). If not provided, a default frame rate may be used. + /// Optional. The sample rate of the audio stream in Hz. If not provided, a default sample rate may be used. + /// Optional. The number of audio channels (e.g., 2 for stereo, 6 for 5.1 surround). If not provided, a default channel count may be used. + /// The created . + public StreamInfo CreateStreamInfo( + string? streamId = null, + string? mimeType = null, + int? bitrate = null, + string? codec = null, + Optional? resolution = null, + Optional? frameRate = null, + Optional? sampleRate = null, + Optional? channels = null) + { + streamId ??= _faker.Random.AlphaNumeric(10); + mimeType ??= _faker.System.MimeType(); + bitrate ??= _faker.Random.Number(1, 10000); + codec ??= _faker.Random.Word(); + resolution ??= Optional.FromNullable(_faker.Random.Bool() ? $"{_faker.Random.Number(100, 4000)}x{_faker.Random.Number(100, 4000)}" : null); + frameRate ??= Optional.FromNullable(_faker.Random.Bool() ? (float?)_faker.Random.Float(1, 120) : null); + sampleRate ??= Optional.FromNullable(_faker.Random.Bool() ? (int?)_faker.Random.Number(8000, 192000) : null); + channels ??= Optional.FromNullable(_faker.Random.Bool() ? (int?)_faker.Random.Number(1, 8) : null); + + ErrorOr streamInfoResult = StreamInfo.Create( + streamId, mimeType, bitrate.Value, codec, resolution.Value, frameRate.Value, sampleRate.Value, channels.Value); + + if (streamInfoResult.IsError) + throw new InvalidOperationException("Failed to create StreamInfo: " + string.Join(", ", streamInfoResult.Errors)); + return streamInfoResult.Value; + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return Enumerable.Range(0, count).Select(_ => CreateStreamInfo()).ToList(); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/ValueObjects/Fixtures/ThumbnailFixture.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/ValueObjects/Fixtures/ThumbnailFixture.cs new file mode 100644 index 00000000..13f23d2d --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/ValueObjects/Fixtures/ThumbnailFixture.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Enums.PhotoLibrary; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class ThumbnailFixture +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly Faker _faker; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public ThumbnailFixture() + { + _faker = new Faker(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + /// + /// Creates a random valid . + /// + /// Optional. The of the thumbnail. If not provided, a random image type is selected. + /// Optional. The byte array representing the image data. If not provided, a random 1KB byte array is generated. + /// A newly created instance. + public Thumbnail CreateThumbnail(ImageType? type = null, byte[]? bytes = null) + { + type ??= _faker.PickRandom(); + bytes ??= _faker.Random.Bytes(1024); // Generate 1KB of random bytes + + return new Thumbnail(type.Value, bytes); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return Enumerable.Range(0, count).Select(_ => CreateThumbnail()).ToList(); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/ValueObjects/PathSegmentTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/ValueObjects/PathSegmentTests.cs new file mode 100644 index 00000000..159b65d2 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/ValueObjects/PathSegmentTests.cs @@ -0,0 +1,151 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FluentAssertions; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects.Fixtures; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class PathSegmentTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly PathSegmentFixture _pathSegmentFixture; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public PathSegmentTests() + { + _pathSegmentFixture = new PathSegmentFixture(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public void Create_WithValidInput_ShouldReturnPathSegment() + { + // Arrange + string name = "testFolder"; + bool isDirectory = true; + bool isDrive = false; + + // Act + ErrorOr result = PathSegment.Create(name, isDirectory, isDrive); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Name.Should().Be(name); + result.Value.IsDirectory.Should().Be(isDirectory); + result.Value.IsDrive.Should().Be(isDrive); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + public void Create_WithInvalidName_ShouldReturnError(string invalidName) + { + // Act + ErrorOr result = PathSegment.Create(invalidName, true, false); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.NameCannotBeEmpty); + } + + [Fact] + public void Equals_WithSameProperties_ShouldReturnTrue() + { + // Arrange + PathSegment segment1 = _pathSegmentFixture.CreatePathSegment("folder", true, false); + PathSegment segment2 = _pathSegmentFixture.CreatePathSegment("folder", true, false); + + // Act + bool result = segment1.Equals(segment2); + + // Assert + result.Should().BeTrue(); + } + + [Fact] + public void Equals_WithDifferentProperties_ShouldReturnFalse() + { + // Arrange + PathSegment segment1 = _pathSegmentFixture.CreatePathSegment("folder1", true, false); + PathSegment segment2 = _pathSegmentFixture.CreatePathSegment("folder2", true, false); + + // Act + bool result = segment1.Equals(segment2); + + // Assert + result.Should().BeFalse(); + } + + [Fact] + public void GetHashCode_WithSameProperties_ShouldReturnSameHashCode() + { + // Arrange + PathSegment segment1 = _pathSegmentFixture.CreatePathSegment("folder", true, false); + PathSegment segment2 = _pathSegmentFixture.CreatePathSegment("folder", true, false); + + // Act + int hashCode1 = segment1.GetHashCode(); + int hashCode2 = segment2.GetHashCode(); + + // Assert + hashCode1.Should().Be(hashCode2); + } + + [Fact] + public void GetHashCode_WithDifferentProperties_ShouldReturnDifferentHashCode() + { + // Arrange + PathSegment segment1 = _pathSegmentFixture.CreatePathSegment("folder1", true, false); + PathSegment segment2 = _pathSegmentFixture.CreatePathSegment("folder2", true, false); + + // Act + int hashCode1 = segment1.GetHashCode(); + int hashCode2 = segment2.GetHashCode(); + + // Assert + hashCode1.Should().NotBe(hashCode2); + } + + [Fact] + public void EqualityOperator_WithSameProperties_ShouldReturnTrue() + { + // Arrange + PathSegment segment1 = _pathSegmentFixture.CreatePathSegment("folder", true, false); + PathSegment segment2 = _pathSegmentFixture.CreatePathSegment("folder", true, false); + + // Act + bool result = segment1 == segment2; + + // Assert + result.Should().BeTrue(); + } + + [Fact] + public void InequalityOperator_WithDifferentProperties_ShouldReturnTrue() + { + // Arrange + PathSegment segment1 = _pathSegmentFixture.CreatePathSegment("folder1", true, false); + PathSegment segment2 = _pathSegmentFixture.CreatePathSegment("folder2", true, false); + + // Act + bool result = segment1 != segment2; + + // Assert + result.Should().BeTrue(); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/ValueObjects/StreamInfoTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/ValueObjects/StreamInfoTests.cs new file mode 100644 index 00000000..2994d324 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/ValueObjects/StreamInfoTests.cs @@ -0,0 +1,186 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FluentAssertions; +using Lumina.Contracts.Enums.FileSystem; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Environment; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Entities.Fixtures; +using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects.Fixtures; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + + +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class StreamInfoTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly StreamInfoFixture _streamInfoFixture; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public StreamInfoTests() + { + _streamInfoFixture = new StreamInfoFixture(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public void Create_WithValidInput_ShouldReturnStreamInfo() + { + // Arrange + string streamId = "testStream"; + string mimeType = "video/mp4"; + int bitrate = 1000; + string codec = "h264"; + Optional resolution = Optional.Some("1920x1080"); + Optional frameRate = Optional.Some(30.0f); + Optional sampleRate = Optional.Some(44100); + Optional channels = Optional.Some(2); + + // Act + ErrorOr result = StreamInfo.Create(streamId, mimeType, bitrate, codec, resolution, frameRate, sampleRate, channels); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.StreamId.Should().Be(streamId); + result.Value.MimeType.Should().Be(mimeType); + result.Value.Bitrate.Should().Be(bitrate); + result.Value.Codec.Should().Be(codec); + result.Value.Resolution.Should().Be(resolution); + result.Value.FrameRate.Should().Be(frameRate); + result.Value.SampleRate.Should().Be(sampleRate); + result.Value.Channels.Should().Be(channels); + } + + [Fact] + public void Create_WithNullStreamId_ShouldReturnError() + { + // Arrange + string? streamId = null; + string mimeType = "video/mp4"; + int bitrate = 1000; + string codec = "h264"; + + // Act + ErrorOr result = StreamInfo.Create(streamId!, mimeType, bitrate, codec, Optional.None(), Optional.None(), Optional.None(), Optional.None()); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.StreamIdCannotBeEmpty); + } + + [Fact] + public void Create_WithNullCodec_ShouldReturnError() + { + // Arrange + string streamId = "testStream"; + string mimeType = "video/mp4"; + int bitrate = 1000; + string? codec = null; + + // Act + ErrorOr result = StreamInfo.Create(streamId, mimeType, bitrate, codec!, Optional.None(), Optional.None(), Optional.None(), Optional.None()); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.CodecCannotBeEmpty); + } + + [Fact] + public void Create_WithNonPositiveBitrate_ShouldReturnError() + { + // Arrange + string streamId = "testStream"; + string mimeType = "video/mp4"; + int bitrate = 0; + string codec = "h264"; + + // Act + ErrorOr result = StreamInfo.Create(streamId, mimeType, bitrate, codec, Optional.None(), Optional.None(), Optional.None(), Optional.None()); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.FileManagement.BitrateMustBeAPositiveNumber); + } + + [Fact] + public void Equals_WithSameProperties_ShouldReturnTrue() + { + // Arrange + StreamInfo info1 = _streamInfoFixture.CreateStreamInfo(); + StreamInfo info2 = _streamInfoFixture.CreateStreamInfo( + info1.StreamId, info1.MimeType, info1.Bitrate, info1.Codec, + info1.Resolution, info1.FrameRate, info1.SampleRate, info1.Channels); + + // Act + bool result = info1.Equals(info2); + + // Assert + result.Should().BeTrue(); + } + + [Fact] + public void Equals_WithDifferentProperties_ShouldReturnFalse() + { + // Arrange + StreamInfo info1 = _streamInfoFixture.CreateStreamInfo(); + StreamInfo info2 = _streamInfoFixture.CreateStreamInfo(); + + // Act + bool result = info1.Equals(info2); + + // Assert + result.Should().BeFalse(); + } + + [Fact] + public void GetHashCode_WithSameProperties_ShouldReturnSameHashCode() + { + // Arrange + StreamInfo info1 = _streamInfoFixture.CreateStreamInfo(); + StreamInfo info2 = _streamInfoFixture.CreateStreamInfo( + info1.StreamId, info1.MimeType, info1.Bitrate, info1.Codec, + info1.Resolution, info1.FrameRate, info1.SampleRate, info1.Channels); + + // Act + int hashCode1 = info1.GetHashCode(); + int hashCode2 = info2.GetHashCode(); + + // Assert + hashCode1.Should().Be(hashCode2); + } + + [Fact] + public void GetHashCode_WithDifferentProperties_ShouldReturnDifferentHashCode() + { + // Arrange + StreamInfo info1 = _streamInfoFixture.CreateStreamInfo(); + StreamInfo info2 = _streamInfoFixture.CreateStreamInfo(); + + // Act + int hashCode1 = info1.GetHashCode(); + int hashCode2 = info2.GetHashCode(); + + // Assert + hashCode1.Should().NotBe(hashCode2); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/ValueObjects/ThumbnailTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/ValueObjects/ThumbnailTests.cs new file mode 100644 index 00000000..177259d8 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/ValueObjects/ThumbnailTests.cs @@ -0,0 +1,137 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Contracts.Enums.PhotoLibrary; +using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects; +using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects.Fixtures; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + + +namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ThumbnailTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly ThumbnailFixture _thumbnailFixture; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public ThumbnailTests() + { + _thumbnailFixture = new ThumbnailFixture(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public void Constructor_ShouldSetPropertiesCorrectly() + { + // Arrange + ImageType type = ImageType.PNG; + byte[] bytes = [1, 2, 3, 4, 5]; + + // Act + Thumbnail thumbnail = new(type, bytes); + + // Assert + thumbnail.Type.Should().Be(type); + thumbnail.Bytes.Should().BeEquivalentTo(bytes); + } + + [Fact] + public void Equals_WithSameProperties_ShouldReturnTrue() + { + // Arrange + Thumbnail thumbnail1 = _thumbnailFixture.CreateThumbnail(); + Thumbnail thumbnail2 = new(thumbnail1.Type, thumbnail1.Bytes); + + // Act + bool result = thumbnail1.Equals(thumbnail2); + + // Assert + result.Should().BeTrue(); + } + + [Fact] + public void Equals_WithDifferentType_ShouldReturnFalse() + { + // Arrange + Thumbnail thumbnail1 = _thumbnailFixture.CreateThumbnail(ImageType.PNG); + Thumbnail thumbnail2 = _thumbnailFixture.CreateThumbnail(ImageType.JPEG, thumbnail1.Bytes); + + // Act + bool result = thumbnail1.Equals(thumbnail2); + + // Assert + result.Should().BeFalse(); + } + + [Fact] + public void Equals_WithDifferentBytes_ShouldReturnFalse() + { + // Arrange + Thumbnail thumbnail1 = _thumbnailFixture.CreateThumbnail(); + Thumbnail thumbnail2 = _thumbnailFixture.CreateThumbnail(thumbnail1.Type); + + // Act + bool result = thumbnail1.Equals(thumbnail2); + + // Assert + result.Should().BeFalse(); + } + + [Fact] + public void GetHashCode_WithSameProperties_ShouldReturnSameHashCode() + { + // Arrange + Thumbnail thumbnail1 = _thumbnailFixture.CreateThumbnail(); + Thumbnail thumbnail2 = new(thumbnail1.Type, thumbnail1.Bytes); + + // Act + int hashCode1 = thumbnail1.GetHashCode(); + int hashCode2 = thumbnail2.GetHashCode(); + + // Assert + hashCode1.Should().Be(hashCode2); + } + + [Fact] + public void GetHashCode_WithDifferentProperties_ShouldReturnDifferentHashCode() + { + // Arrange + Thumbnail thumbnail1 = _thumbnailFixture.CreateThumbnail(); + Thumbnail thumbnail2 = _thumbnailFixture.CreateThumbnail(); + + // Act + int hashCode1 = thumbnail1.GetHashCode(); + int hashCode2 = thumbnail2.GetHashCode(); + + // Assert + hashCode1.Should().NotBe(hashCode2); + } + + [Fact] + public void GetEqualityComponents_ShouldReturnTypeAndBytes() + { + // Arrange + Thumbnail thumbnail = _thumbnailFixture.CreateThumbnail(); + + // Act + List components = thumbnail.GetEqualityComponents().ToList(); + + // Assert + components.Should().HaveCount(2); + components[0].Should().Be(thumbnail.Type); + components[1].Should().BeEquivalentTo(thumbnail.Bytes); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Lumina.Domain.UnitTests.csproj b/tests/UnitTests/Lumina.Domain.UnitTests/Lumina.Domain.UnitTests.csproj index be4836a0..c08300c3 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Lumina.Domain.UnitTests.csproj +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Lumina.Domain.UnitTests.csproj @@ -11,7 +11,9 @@ + +