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/src/Lumina.Presentation.Web/ViewComponents/FileSystemBrowserViewComponent.cs b/src/Lumina.Presentation.Web/ViewComponents/FileSystemBrowserViewComponent.cs
index 3279c4f5..8dc53dd2 100644
--- a/src/Lumina.Presentation.Web/ViewComponents/FileSystemBrowserViewComponent.cs
+++ b/src/Lumina.Presentation.Web/ViewComponents/FileSystemBrowserViewComponent.cs
@@ -3,6 +3,8 @@ using Lumina.Presentation.Web.Common.Enums.FileSystem;
using Lumina.Presentation.Web.Common.Models.Configuration;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
+using System.Runtime.InteropServices;
+
#endregion
namespace Lumina.Presentation.Web.ViewComponents;
@@ -38,7 +40,7 @@ public class FileSystemBrowserViewComponent : ViewComponent
{
return View(new
{
- Path = @"C:\",
+ Path = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ? @"/" : @"C:\",
ServerBasePath = $"{_serverConfigurationModel.BaseAddress}:{_serverConfigurationModel.Port}/api/v{_serverConfigurationModel.ApiVersion}/",
ClientBasePath = "http://localhost:5012/", // TODO: take from appsettings or environment
ViewMode = FileSystemViewMode.List,
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..4bc2d0a2
--- /dev/null
+++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Services/DirectoryProviderServiceTests.cs
@@ -0,0 +1,1012 @@
+#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;
+using System.Runtime.InteropServices;
+using System.Text;
+
+#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;
+ private static readonly bool s_isLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
+ private readonly string _pathSource = s_isLinux ? "/Source" : @"C:\Source";
+ private readonly string _pathSourceSubDir = s_isLinux ? "/Source/SubDir" : @"C:\Source\SubDir";
+ private readonly string _pathSourceSubDir1 = s_isLinux ? "/Source/SubDir1" : @"C:\Source\SubDir1";
+ private readonly string _pathSourceSubDir2 = s_isLinux ? "/Source/SubDir2" : @"C:\Source\SubDir2";
+ private readonly string _pathSourceFile1 = s_isLinux ? "/Source/file1.txt" : @"C:\Source\file1.txt";
+ private readonly string _pathSourceFile2 = s_isLinux ? "/Source/file2.txt" : @"C:\Source\file2.txt";
+ private readonly string _pathDestinationFile1 = s_isLinux ? "/Destination/file1.txt" : @"C:\Destination\file1.txt";
+ private readonly string _pathDestinationFile2 = s_isLinux ? "/Destination/file2.txt" : @"C:\Destination\file2.txt";
+ private readonly string _pathDestination = s_isLinux ? "/Destination" : @"C:\Destination";
+ private readonly string _pathDestinationSubDir = s_isLinux ? "/Destination/SubDir" : @"C:\Destination\SubDir";
+ private readonly string _pathDestinationSubDir1 = s_isLinux ? "/Destination/SubDir1" : @"C:\Destination\SubDir1";
+ private readonly string _pathDestinationSubDir2 = s_isLinux ? "/Destination/SubDir2" : @"C:\Destination\SubDir2";
+ private readonly string _pathDestinationFile = s_isLinux ? "/Destination/file.txt" : @"C:\Destination\file.txt";
+ private readonly string _pathVisible1 = s_isLinux ? "/Visible" : @"C:\Visible";
+ private readonly string _pathHidden1 = s_isLinux ? "/Hidden" : @"C:\Hidden";
+ private readonly string _pathVisible2 = s_isLinux ? "/Visible/" : @"C:\Visible\";
+ private readonly string _pathHidden2 = s_isLinux ? "/Hidden/" : @"C:\Hidden\";
+ private readonly string _pathValid1 = s_isLinux ? "/Valid" : @"C:\Valid";
+ private readonly string _pathInvalid1 = s_isLinux ? "/Invalid" : @"C:\Invalid";
+ private readonly string _pathValid2 = s_isLinux ? "/Valid/" : @"C:\Valid\";
+ private readonly string _pathInvalid2 = s_isLinux ? "/Invalid/" : @"C:\Invalid\";
+ private readonly char _dirSeparator = s_isLinux ? '/' : '\\';
+ #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(_dirSeparator);
+
+ // 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 + _dirSeparator));
+ }
+
+ [Fact]
+ public void GetSubdirectoryPaths_WhenIncludeHiddenElementsIsFalse_ShouldExcludeHiddenDirectories()
+ {
+ // Arrange
+ FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId();
+ string[] subdirectories = [_pathVisible1, _pathHidden1];
+ _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory, false).Returns(true);
+ _mockFileSystem.Directory.GetDirectories(path.Path).Returns(subdirectories);
+ _mockFileSystem.Path.DirectorySeparatorChar.Returns(_dirSeparator);
+ _mockFileSystem.File.GetAttributes(_pathVisible1).Returns(FileAttributes.Directory);
+ _mockFileSystem.File.GetAttributes(_pathHidden1).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(_pathVisible2);
+ }
+
+ [Fact]
+ public void GetSubdirectoryPaths_WhenIncludeHiddenElementsIsTrue_ShouldIncludeHiddenDirectories()
+ {
+ // Arrange
+ FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId();
+ string[] subdirectories = [_pathVisible1, _pathHidden1];
+ _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory, false).Returns(true);
+ _mockFileSystem.Directory.GetDirectories(path.Path).Returns(subdirectories);
+ _mockFileSystem.Path.DirectorySeparatorChar.Returns(_dirSeparator);
+ _mockFileSystem.File.GetAttributes(_pathVisible1).Returns(FileAttributes.Directory);
+ _mockFileSystem.File.GetAttributes(_pathHidden1).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([_pathVisible2, _pathHidden2]);
+ }
+
+ [Fact]
+ public void GetSubdirectoryPaths_WhenGetAttributesThrowsException_ShouldStillAddDirectory()
+ {
+ // Arrange
+ FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId();
+ string[] subdirectories = [_pathValid1, _pathInvalid1];
+ _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory, false).Returns(true);
+ _mockFileSystem.Directory.GetDirectories(path.Path).Returns(subdirectories);
+ _mockFileSystem.Path.DirectorySeparatorChar.Returns(_dirSeparator);
+ _mockFileSystem.File.GetAttributes(_pathValid1).Returns(FileAttributes.Directory);
+ _mockFileSystem.File.GetAttributes(_pathInvalid1).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(_pathInvalid2);
+ result.Value.Last().Path.Should().Be(_pathValid2);
+ }
+
+ [Fact]
+ public void GetSubdirectoryPaths_ShouldOrderDirectoriesAlphabetically()
+ {
+ // Arrange
+ FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId();
+ string[] subdirectories = s_isLinux
+ ? new[] { "/C", "/A", "/B" }
+ : new[] { @"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(_dirSeparator);
+ _mockFileSystem.File.GetAttributes(Arg.Any()).Returns(FileAttributes.Directory);
+ string[] expectedPaths = s_isLinux
+ ? new[] { "/A/", "/B/", "/C/" }
+ : new[] { @"C:\A\", @"C:\B\", @"C:\C\" };
+
+ // Act
+ ErrorOr> result = _sut.GetSubdirectoryPaths(path, false);
+
+ // Assert
+ result.IsError.Should().BeFalse();
+ result.Value.Select(x => x.Path).Should().BeEquivalentTo(expectedPaths, 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 = s_isLinux
+ ? "/folder/subfolder/file.txt"
+ : @"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 = s_isLinux
+ ? "/folder/subfolder/"
+ : @"C:\folder\subfolder\";
+ FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(fullPath);
+ _mockFileSystem.Path.GetFileName(fullPath[..^1]).Returns("subfolder");
+ _mockFileSystem.Path.DirectorySeparatorChar.Returns(_dirSeparator);
+
+ // 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 = s_isLinux
+ ? "/C/"
+ : @"/";
+ FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(fullPath);
+ _mockFileSystem.Path.GetFileName(fullPath[..^1]).Returns(string.Empty);
+ _mockFileSystem.Path.DirectorySeparatorChar.Returns(_dirSeparator);
+
+ // 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 = s_isLinux
+ ? "/Parent/NewDirectory"
+ : @"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(_pathSource);
+ FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestination);
+ 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(_pathSource);
+ FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestination);
+ string expectedNewDirectoryPath = s_isLinux
+ ? "/Destination - Copy (1)"
+ : @"C:\Destination - Copy (1)";
+ bool overrideExisting = false;
+
+ _mockFileSystem.Directory.Exists(sourcePath.Path).Returns(true);
+ _mockFileSystem.Directory.Exists(destinationPath.Path).Returns(true);
+ _mockFileSystem.Directory.Exists(_pathDestination).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(_pathSource);
+ FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestination);
+ bool overrideExisting = true;
+
+
+ // ensure all relevant directories exist
+ _mockFileSystem.Directory.Exists(_pathSource).Returns(true);
+ _mockFileSystem.Directory.Exists(_pathSourceSubDir).Returns(true);
+ _mockFileSystem.Directory.Exists(_pathDestination).Returns(false);
+ _mockFileSystem.Directory.CreateDirectory(Arg.Any()).Returns(callInfo => {
+ IDirectoryInfo mockDirInfo = Substitute.For();
+ mockDirInfo.FullName.Returns(callInfo.Arg());
+ return mockDirInfo;
+ });
+
+ 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(_pathSourceSubDir);
+
+ IDirectoryInfo sourceDirectoryInfo = Substitute.For();
+ sourceDirectoryInfo.GetFiles().Returns([mockFile]);
+ sourceDirectoryInfo.GetDirectories().Returns([mockSubDir]);
+ _mockFileSystem.DirectoryInfo.New(_pathSource).Returns(sourceDirectoryInfo);
+
+ // mock subdirectory info
+ IDirectoryInfo subDirInfo = Substitute.For();
+ subDirInfo.GetFiles().Returns([]);
+ subDirInfo.GetDirectories().Returns([]);
+ _mockFileSystem.DirectoryInfo.New(_pathSourceSubDir).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(_pathDestination);
+ _mockFileSystem.Directory.Received(1).CreateDirectory(_pathDestination);
+ _mockFileSystem.Directory.Received(1).CreateDirectory(_pathDestinationSubDir);
+ mockFile.Received(1).CopyTo(_pathDestinationFile, overrideExisting);
+ _mockFileSystem.File.Received(1).SetAttributes(_pathDestinationFile, 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(
+ s_isLinux ? "/NonExistentSource" : @"C:\NonExistentSource"
+ );
+ FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestination);
+ 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(_pathSource);
+ FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestination);
+ 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(_pathSource);
+ FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestination);
+ bool overrideExisting = true;
+
+ _mockFileSystem.Directory.Exists(sourcePath.Path).Returns(true);
+ _mockFileSystem.Directory.Exists(destinationPath.Path).Returns(true);
+
+ _mockFileSystem.Directory.GetFiles(sourcePath.Path).Returns([_pathSourceFile1]);
+ _mockFileSystem.Directory.GetDirectories(sourcePath.Path).Returns([_pathSourceSubDir]);
+
+ _mockFileSystem.Directory.GetFiles(_pathSourceSubDir).Returns([]);
+ _mockFileSystem.Directory.GetDirectories(_pathSourceSubDir).Returns([]);
+
+ _mockFileSystem.Path.GetFileName(_pathSourceFile1).Returns("file1.txt");
+ _mockFileSystem.Path.GetFileName(_pathSourceSubDir).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(_pathSourceFile1, _pathDestinationFile1);
+ _mockFileSystem.Directory.Received(1).Move(
+ _pathSourceSubDir,
+ s_isLinux ? "/Destination/SubDir" : @"C:\Destination\SubDir"
+ );
+ _mockFileSystem.Directory.Received(1).Delete(sourcePath.Path);
+ }
+
+ [Fact]
+ public void MoveDirectory_WhenExceptionOccurs_ShouldReturnDirectoryMoveError()
+ {
+ // Arrange
+ FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathSource);
+ FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestination);
+ 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(_pathSource);
+ FileSystemPathId destPath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestination);
+ bool overwrite = true;
+
+ _mockFileSystem.Directory.Exists(sourcePath.Path).Returns(true);
+ _mockFileSystem.Directory.Exists(destPath.Path).Returns(true);
+
+ _mockFileSystem.Directory.GetFiles(sourcePath.Path).Returns([_pathSourceFile1, _pathSourceFile2]);
+ _mockFileSystem.Directory.GetDirectories(sourcePath.Path).Returns([_pathSourceSubDir1, _pathSourceSubDir2]);
+
+ _mockFileSystem.Path.GetFileName(_pathSourceFile1).Returns("file1.txt");
+ _mockFileSystem.Path.GetFileName(_pathSourceFile2).Returns("file2.txt");
+ _mockFileSystem.Path.GetFileName(_pathSourceSubDir1).Returns("SubDir1");
+ _mockFileSystem.Path.GetFileName(_pathSourceSubDir2).Returns("SubDir2");
+
+ _mockFileSystem.File.Exists(_pathDestinationFile1).Returns(true);
+ _mockFileSystem.File.Exists(_pathDestinationFile2).Returns(false);
+
+ _mockFileSystem.Directory.Exists(_pathDestinationSubDir1).Returns(true);
+ _mockFileSystem.Directory.Exists(_pathDestinationSubDir2).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(_pathDestinationFile1);
+ _mockFileSystem.File.Received(1).Move(_pathSourceFile1, _pathDestinationFile1);
+ _mockFileSystem.File.Received(1).Move(_pathSourceFile2, _pathDestinationFile2);
+ _mockFileSystem.Directory.Received(1).Move(_pathSourceSubDir2, _pathDestinationSubDir2);
+ _mockFileSystem.Directory.Received(1).Delete(sourcePath.Path);
+ }
+
+ [Fact]
+ public void MoveDirectory_WhenOverwriteIsFalse_ShouldMoveOnlyNonExistingFiles()
+ {
+ // Arrange
+ FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathSource);
+ FileSystemPathId destPath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestination);
+ bool overwrite = false;
+
+ _mockFileSystem.Directory.Exists(sourcePath.Path).Returns(true);
+ _mockFileSystem.Directory.Exists(destPath.Path).Returns(true);
+
+ _mockFileSystem.Directory.GetFiles(sourcePath.Path).Returns([_pathSourceFile1, _pathSourceFile2]);
+ _mockFileSystem.Directory.GetDirectories(sourcePath.Path).Returns([]);
+
+ _mockFileSystem.Path.GetFileName(_pathSourceFile1).Returns("file1.txt");
+ _mockFileSystem.Path.GetFileName(_pathSourceFile2).Returns("file2.txt");
+
+ _mockFileSystem.File.Exists(_pathDestinationFile1).Returns(true);
+ _mockFileSystem.File.Exists(_pathDestinationFile2).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([_pathSourceFile2]);
+
+ // 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(_pathSourceFile1, _pathDestinationFile1);
+ _mockFileSystem.File.Received(1).Move(_pathSourceFile2, _pathDestinationFile2);
+ _mockFileSystem.Directory.DidNotReceive().Delete(sourcePath.Path);
+ }
+
+ [Fact]
+ public void MergeDirectories_WhenSourceIsEmpty_ShouldDeleteSourceDirectory()
+ {
+ // Arrange
+ string sourceDir = _pathSource;
+ string destDir = _pathDestination;
+ 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(_pathSource);
+ FileSystemPathId destPath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestination);
+ bool overwrite = true;
+
+ _mockFileSystem.Directory.Exists(sourcePath.Path).Returns(true);
+ _mockFileSystem.Directory.Exists(destPath.Path).Returns(true);
+
+ _mockFileSystem.Directory.Exists(_pathSourceSubDir).Returns(true);
+ _mockFileSystem.Directory.Exists(s_isLinux ? "/Destination/SubDir" : @"C:\Destination\SubDir").Returns(true);
+
+ _mockFileSystem.Directory.GetFiles(sourcePath.Path).Returns([]);
+ _mockFileSystem.Directory.GetDirectories(sourcePath.Path).Returns([_pathSourceSubDir]);
+
+ _mockFileSystem.Directory.GetFiles(_pathSourceSubDir).Returns(
+ s_isLinux ? ["/Source/SubDir/file.txt"] : [@"C:\Source\SubDir\file.txt"]
+ );
+ _mockFileSystem.Directory.GetDirectories(_pathSourceSubDir).Returns([]);
+
+ _mockFileSystem.Path.GetFileName(_pathSourceSubDir).Returns("SubDir");
+ _mockFileSystem.Path.GetFileName(s_isLinux ? "/Source/SubDir/file.txt" : @"C:\Source\SubDir\file.txt").Returns("file.txt");
+
+ _mockFileSystem.File.Exists(s_isLinux ? "/Destination/SubDir/file.txt" : @"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([_pathSourceSubDir]);
+ _mockFileSystem.Directory.EnumerateFileSystemEntries(_pathSourceSubDir).Returns([]);
+
+ // Act
+ ErrorOr result = _sut.MoveDirectory(sourcePath, destPath, overwrite);
+
+ // Assert
+ result.IsError.Should().BeFalse();
+ result.Value.Should().Be(destPath);
+ _mockFileSystem.File.Received(1).Move(
+ s_isLinux ? "/Source/SubDir/file.txt" : @"C:\Source\SubDir\file.txt",
+ s_isLinux ? "/Destination/SubDir/file.txt" : @"C:\Destination\SubDir\file.txt"
+ );
+ _mockFileSystem.Directory.Received(1).Delete(_pathSourceSubDir);
+ _mockFileSystem.Directory.DidNotReceive().Delete(sourcePath.Path);
+ }
+
+ [Fact]
+ public void RenameDirectory_WhenParentDirectoryIsWritable_ShouldRenameSuccessfully()
+ {
+ // Arrange
+ FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(
+ s_isLinux ? "/OldName" : @"C:\OldName"
+ );
+ string newName = "NewName";
+ string parentPath = s_isLinux ? "/" : @"C:\";
+ string newPath = s_isLinux ? "/NewName" : @"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(
+ s_isLinux ? "/OldName" : @"C:\OldName"
+ );
+ string newName = "NewName";
+ string parentPath = s_isLinux ? "/" : @"C:\";
+ string newPath = s_isLinux ? "/NewName" : @"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(
+ s_isLinux ? "/OldName" : @"C:\OldName"
+ );
+ string newName = "NewName";
+ string parentPath = s_isLinux ? "/" : @"C:\";
+ string newPath = s_isLinux ? "/NewName" : @"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(
+ s_isLinux ? "/OldName" : @"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(
+ s_isLinux ? "/OldName" : @"C:\OldName"
+ );
+ string newName = "NewName";
+ string parentPath = s_isLinux ? "/" : @"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(
+ s_isLinux ? "/DirectoryToDelete" : @"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(
+ s_isLinux ? "/DirectoryToDelete" : @"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..d0559ce3
--- /dev/null
+++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Aggregates/FileManagementAggregate/Services/DirectoryServiceTests.cs
@@ -0,0 +1,790 @@
+#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;
+using System.Runtime.InteropServices;
+
+#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;
+ private static readonly bool s_isLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
+ private readonly string _pathDirTest = s_isLinux ? "/TestDir" : @"C:\TestDir";
+ private readonly string _pathDirTestSubDir1 = s_isLinux ? "/TestDir/Sub1" : @"C:\TestDir\Sub1";
+ private readonly string _pathDirTestSubDir2 = s_isLinux ? "/TestDir/Sub2" : @"C:\TestDir\Sub2";
+ private readonly char _dirSeparator = s_isLinux ? '/' : '\\';
+ #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 = _pathDirTest;
+ bool includeHiddenElements = false;
+ FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path);
+ FileSystemPathId[] subPaths =
+ [
+ _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDirTestSubDir1),
+ _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDirTestSubDir2)
+ ];
+
+ _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 = _pathDirTest;
+ 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 = _pathDirTest;
+ bool includeHiddenElements = false;
+ FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path);
+ FileSystemPathId subPath = _fileSystemPathIdFixture.CreateFileSystemPathId(
+ s_isLinux ? "/TestDir/InaccessibleSub" : @"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(_pathDirTestSubDir1),
+ _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDirTestSubDir2)
+ ];
+
+ _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(
+ s_isLinux ? "/TestDir/InaccessibleSub" : @"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(_pathDirTest);
+ bool includeHiddenElements = false;
+ FileSystemPathId[] subPaths =
+ [
+ _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDirTestSubDir1),
+ _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDirTestSubDir2)
+ ];
+
+ _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(_pathDirTest);
+ 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(_pathDirTest);
+ bool includeHiddenElements = false;
+ FileSystemPathId subPath = _fileSystemPathIdFixture.CreateFileSystemPathId(
+ s_isLinux ? "/TestDir/InaccessibleSub" : @"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