Merge pull request #14 from BinaryAlley/refactor/add-file-system-domain-unit-tests

Adds Domain layer unit tests for file system browser dialog
This commit is contained in:
BinaryAlley authored and GitHub committed 2024-10-06 17:43:29 +03:00
commit 30a07f306d
59 files changed
+9043 -149

No files matched your search

@@ -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")]
[assembly: InternalsVisibleTo("Lumina.Application.UnitTests")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
@@ -1,24 +1,87 @@
namespace Lumina.Contracts.Enums.PhotoLibrary;
namespace Lumina.Contracts.Enums.PhotoLibrary;
/// <summary>
/// Enumeration for known image types.
/// </summary>
public enum ImageType
{
/// <summary>
/// No image type specified.
/// </summary>
None,
/// <summary>
/// Bitmap image format.
/// </summary>
BMP,
/// <summary>
/// Graphics Interchange Format (GIF).
/// </summary>
GIF,
/// <summary>
/// Portable Network Graphics (PNG) format.
/// </summary>
PNG,
/// <summary>
/// Tagged Image File Format (TIFF).
/// </summary>
TIFF,
/// <summary>
/// Joint Photographic Experts Group (JPEG) format.
/// </summary>
JPEG,
/// <summary>
/// Canon-specific JPEG format.
/// </summary>
JPEG_CANON,
/// <summary>
/// Unknown JPEG format.
/// </summary>
JPEG_UNKNOWN,
/// <summary>
/// Macintosh Picture (PICT) format.
/// </summary>
PICT,
/// <summary>
/// Icon (ICO) format.
/// </summary>
ICO,
/// <summary>
/// Photoshop Document (PSD) format.
/// </summary>
PSD,
/// <summary>
/// JPEG 2000 format.
/// </summary>
JPEG2000,
/// <summary>
/// AV1 Image File Format (AVIF).
/// </summary>
AVIF,
/// <summary>
/// Web Picture (WEBP) format.
/// </summary>
WEBP,
/// <summary>
/// Truevision TGA format.
/// </summary>
TGA,
SVG,
}
/// <summary>
/// Scalable Vector Graphics (SVG) format.
/// </summary>
SVG
}
@@ -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")]
[assembly: InternalsVisibleTo("Lumina.DataAccess.UnitTests")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
@@ -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<IPlatformContextManager, PlatformContextManager>();
services.AddScoped<IUnixPathStrategy, UnixPathStrategy>();
services.AddScoped<IWindowsPathStrategy, WindowsPathStrategy>();
services.AddScoped<IOperatingSystemInfo, OperatingSystemInfo>();
services.AddSingleton<IFileSystem, FileSystem>();
return services;
}
#endregion
}
}
@@ -143,9 +143,9 @@ public class DirectoryService : IDirectoryService
ErrorOr<FileSystemPathId> newDirectoryPathResult = _environmentContext.DirectoryProviderService.CreateDirectory(path, name);
if (newDirectoryPathResult.IsError)
return newDirectoryPathResult.Errors;
ErrorOr<string> dirNameResult = _environmentContext.DirectoryProviderService.GetFileName(path);
ErrorOr<Optional<DateTime>> dateModifiedResult = _environmentContext.DirectoryProviderService.GetLastWriteTime(path);
ErrorOr<Optional<DateTime>> dateCreatedResult = _environmentContext.DirectoryProviderService.GetCreationTime(path);
ErrorOr<string> dirNameResult = _environmentContext.DirectoryProviderService.GetFileName(newDirectoryPathResult.Value);
ErrorOr<Optional<DateTime>> dateModifiedResult = _environmentContext.DirectoryProviderService.GetLastWriteTime(newDirectoryPathResult.Value);
ErrorOr<Optional<DateTime>> dateCreatedResult = _environmentContext.DirectoryProviderService.GetCreationTime(newDirectoryPathResult.Value);
// if any error occurred, mark directory as Inaccessible
if (dirNameResult.IsError || dateModifiedResult.IsError || dateCreatedResult.IsError)
{
@@ -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);
@@ -117,6 +117,8 @@ public class FileService : IFileService
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a copied file, or an error.</returns>
public ErrorOr<File> 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
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a moved file, or an error.</returns>
public ErrorOr<File> 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;
@@ -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
/// <summary>
/// Service for file system permissions.
/// </summary>
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
}
}
@@ -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;
}
/// <summary>
@@ -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
/// <returns>An <see cref="ErrorOr{TValue}"/> containing the combined path, or an error.</returns>
public ErrorOr<string> CombinePath(string path, string name)
{
if (string.IsNullOrWhiteSpace(path) || string.IsNullOrWhiteSpace(name))
return Errors.FileManagement.InvalidPath;
ErrorOr<FileSystemPathId> newPathResult = FileSystemPathId.Create(path);
if (newPathResult.IsError)
return newPathResult.Errors;
@@ -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
/// <returns>An <see cref="ErrorOr{TValue}"/> containing the path segments, or an error.</returns>
public ErrorOr<IEnumerable<PathSegment>> 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<ErrorOr<PathSegment>> getPathSegmentsResults = GetPathSegments();
foreach (ErrorOr<PathSegment> getPathSegmentsResult in getPathSegmentsResults)
@@ -99,20 +98,39 @@ public class WindowsPathStrategy : IWindowsPathStrategy
return ErrorOrFactory.From(getPathSegmentsResults.Select(getPathSegmentsResult => getPathSegmentsResult.Value));
IEnumerable<ErrorOr<PathSegment>> 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<PathSegment> 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<FileSystemPathId> 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<FileSystemPathId> 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<IEnumerable<PathSegment>> parseResult = ParsePath(path);
if (parseResult.IsError)
return parseResult.Errors;
List<PathSegment> 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
@@ -0,0 +1,20 @@
#region ========================================================================= USING =====================================================================================
using System.Runtime.InteropServices;
#endregion
namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform;
/// <summary>
/// Interface for checking the type of the current Operating System platform.
/// </summary>
public interface IOperatingSystemInfo
{
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Determines if the current Operating System plaform is <paramref name="platform"/>.
/// </summary>
/// <param name="platform">The Operating System platform to check against.</param>
/// <returns><see langword="true"/> if tthe current Operating System platform is equal to <paramref name="platform"/>, <see langword="false"/> otherwise.</returns>
bool IsOSPlatform(OSPlatform platform);
#endregion
}
@@ -0,0 +1,25 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
#endregion
namespace Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform;
/// <summary>
/// Class for checking the type of the current Operating System platform.
/// </summary>
[ExcludeFromCodeCoverage]
internal class OperatingSystemInfo : IOperatingSystemInfo
{
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Determines if the current Operating System plaform is <paramref name="platform"/>.
/// </summary>
/// <param name="platform">The Operating System platform to check against.</param>
/// <returns><see langword="true"/> if tthe current Operating System platform is equal to <paramref name="platform"/>, <see langword="false"/> otherwise.</returns>
public bool IsOSPlatform(OSPlatform platform)
{
return RuntimeInformation.IsOSPlatform(platform);
}
#endregion
}
@@ -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 <see cref="PlatformContextManager"/> class.
/// </summary>
/// <param name="platformContextFactory">Injected factory for creating platform contexts.</param>
public PlatformContextManager(IPlatformContextFactory platformContextFactory)
/// <param name="operatingSystemInfo">Injected class for checking the platform type of the current Operating System.</param>
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
}
}
@@ -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
/// <summary>
/// Gets the path strategy for Unix platforms.
/// </summary>
public IPathStrategy PathStrategy { get; private set; }
public IPathStrategy PathStrategy { get; }
#endregion
#region ====================================================================== CTOR =====================================================================================
@@ -32,4 +32,4 @@ internal class UnixPlatformContext : IUnixPlatformContext
PathStrategy = unixPathStrategy;
}
#endregion
}
}
@@ -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
/// <summary>
/// Gets the path strategy for Windows platforms.
/// </summary>
public IPathStrategy PathStrategy { get; private set; }
public IPathStrategy PathStrategy { get; }
#endregion
#region ====================================================================== CTOR =====================================================================================
@@ -32,4 +32,4 @@ public class WindowsPlatformContext : IWindowsPlatformContext
PathStrategy = windowsPathStrategy;
}
#endregion
}
}
@@ -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;
/// <summary>
/// Value Object for the Id of a book.
/// </summary>
[DebuggerDisplay("{Value}")]
public sealed class FileSystemId : EntityId<Guid>
{
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="FileSystemId"/> class.
/// </summary>
/// <param name="value">The value representing this object.</param>
private FileSystemId(Guid value) : base(value)
{
}
#endregion
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Creates a new instance of the <see cref="FileSystemId"/> class.
/// </summary>
/// <returns>The created <see cref="FileSystemId"/> instance.</returns>
public static FileSystemId CreateUnique()
{
return new FileSystemId(Guid.NewGuid());
}
/// <summary>
/// Creates a new instance of the <see cref="FileSystemId"/> class, from a pre-existing <paramref name="value"/>.
/// </summary>
/// <param name="value">The value used to create the <see cref="FileSystemId"/> instance.</param>
/// <returns>The created <see cref="FileSystemId"/> instance.</returns>
public static FileSystemId Create(Guid value)
{
return new FileSystemId(value);
}
/// <inheritdoc/>
public override IEnumerable<object> GetEqualityComponents()
{
yield return Value;
}
#endregion
}
+3 -2
View File
@@ -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")]
[assembly: InternalsVisibleTo("Lumina.Domain.UnitTests")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
@@ -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")]
[assembly: InternalsVisibleTo("Lumina.Infrastructure.UnitTests")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
@@ -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")]
[assembly: InternalsVisibleTo("Lumina.Presentation.Api.UnitTests")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
@@ -17,3 +17,4 @@ using System.Runtime.InteropServices;
[assembly: Guid("4E3EEA67-7C92-4588-9183-03140627D564")]
[assembly: InternalsVisibleTo("Lumina.Presentation.Web.UnitTests")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
@@ -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,
@@ -37,7 +37,14 @@ public class DirectoryFixture
/// <summary>
/// Creates a random valid <see cref="Directory"/>.
/// </summary>
/// <returns>The created <see cref="Directory"/>.</returns>
/// <param name="path">Optional. The directory path. If not provided, a random path is generated.</param>
/// <param name="name">Optional. The directory name. If not provided, a random name is generated.</param>
/// <param name="dateCreated">Optional. The directory's creation date. If not provided, a random past date is generated.</param>
/// <param name="dateModified">Optional. The directory's modification date. If not provided, a recent date is generated.</param>
/// <param name="status">Optional. The directory's status. If not provided, a random status is assigned.</param>
/// <param name="childItems">Optional. A list of child items to be added to the directory.</param>
/// <returns>A newly created Directory instance.</returns>
/// <exception cref="InvalidOperationException">Thrown if the Directory creation fails.</exception>
public Directory CreateDirectory(
string? path = null,
string? name = null,
@@ -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;
@@ -0,0 +1,137 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Domain.Common.Primitives;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Common.Primitives;
/// <summary>
/// Contains unit tests for the <see cref="Optional{T}"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class OptionalTests
{
#region ===================================================================== METHODS ===================================================================================
[Fact]
public void Some_WhenCreatingOptionalWithValue_ShouldHaveValueAndCorrectValue()
{
// Arrange
int value = 42;
// Act
Optional<int> optional = Optional<int>.Some(value);
// Assert
optional.HasValue.Should().BeTrue();
optional.Value.Should().Be(value);
}
[Fact]
public void None_WhenCreatingOptionalWithoutValue_ShouldNotHaveValueAndHaveDefaultValue()
{
// Arrange & Act
Optional<int> optional = Optional<int>.None();
// Assert
optional.HasValue.Should().BeFalse();
optional.Value.Should().Be(default);
}
[Fact]
public void ImplicitConversion_WhenConvertingValueToOptional_ShouldCreateOptionalWithValue()
{
// Arrange
string value = "test";
// Act
Optional<string> optional = value;
// Assert
optional.HasValue.Should().BeTrue();
optional.Value.Should().Be(value);
}
[Fact]
public void FromNullable_WhenCreatingFromNonNullReferenceType_ShouldCreateOptionalWithValue()
{
// Arrange
string? nullableValue = "test";
// Act
Optional<string> optional = Optional<string>.FromNullable(nullableValue);
// Assert
optional.HasValue.Should().BeTrue();
optional.Value.Should().Be(nullableValue);
}
[Fact]
public void FromNullable_WhenCreatingFromNullReferenceType_ShouldCreateOptionalWithoutValue()
{
// Arrange
string? nullableValue = null;
// Act
Optional<string> optional = Optional<string>.FromNullable(nullableValue);
// Assert
optional.HasValue.Should().BeFalse();
optional.Value.Should().BeNull();
}
[Fact]
public void FromNullable_WhenCreatingFromNonNullValueType_ShouldCreateOptionalWithValue()
{
// Arrange
int? nullableValue = 42;
// Act
Optional<int> optional = Optional<int>.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<int> optional = Optional<int>.FromNullable(nullableValue);
// Assert
optional.HasValue.Should().BeFalse();
optional.Value.Should().Be(default);
}
[Fact]
public void ToString_WhenOptionalHasValue_ShouldReturnValueToString()
{
// Arrange
Optional<int> optional = Optional<int>.Some(42);
// Act
string result = optional.ToString();
// Assert
result.Should().Be("42");
}
[Fact]
public void ToString_WhenOptionalHasNoValue_ShouldReturnEmptyString()
{
// Arrange
Optional<int> optional = Optional<int>.None();
// Act
string result = optional.ToString();
// Assert
result.Should().BeEmpty();
}
#endregion
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="Directory"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DirectoryTests
{
#region ===================================================================== METHODS ===================================================================================
[Fact]
public void Create_WhenCalledWithValidParameters_ShouldReturnSuccessfulResult()
{
// Arrange
string path = "/valid/path";
string name = "TestDirectory";
Optional<DateTime> dateCreated = DateTime.Now;
Optional<DateTime> dateModified = DateTime.Now;
// Act
ErrorOr<Directory> 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<DateTime> dateCreated = DateTime.Now;
Optional<DateTime> dateModified = DateTime.Now;
// Act
ErrorOr<Directory> 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<FileSystemPathId> pathIdResult = FileSystemPathId.Create("/valid/path");
pathIdResult.IsError.Should().BeFalse();
FileSystemPathId pathId = pathIdResult.Value;
string name = "TestDirectory";
Optional<DateTime> dateCreated = DateTime.Now;
Optional<DateTime> dateModified = DateTime.Now;
// Act
ErrorOr<Directory> 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<Directory> directoryResult = Directory.Create("/valid/path", "TestDirectory", Optional<DateTime>.None(), Optional<DateTime>.None());
directoryResult.IsError.Should().BeFalse();
Directory directory = directoryResult.Value;
DateTime newDate = DateTime.Now;
// Act
ErrorOr<Updated> result = directory.UpdateLastModified(newDate);
// Assert
result.IsError.Should().BeFalse();
directory.DateModified.Value.Should().Be(newDate);
}
[Fact]
public void AddItem_WhenCalled_ShouldAddItemToCollection()
{
// Arrange
ErrorOr<Directory> directoryResult = Directory.Create("/valid/path", "TestDirectory", Optional<DateTime>.None(), Optional<DateTime>.None());
directoryResult.IsError.Should().BeFalse();
Directory directory = directoryResult.Value;
FileSystemItem item = new FileSystemItemFixture(FileSystemPathId.Create("/mock/path").Value, "MockItem", FileSystemItemType.File);
// Act
ErrorOr<Updated> result = directory.AddItem(item);
// Assert
result.IsError.Should().BeFalse();
directory.Items.Should().Contain(item);
}
[Fact]
public void RemoveItem_WhenCalledWithExistingItem_ShouldRemoveItemFromCollection()
{
// Arrange
ErrorOr<Directory> directoryResult = Directory.Create("/valid/path", "TestDirectory", Optional<DateTime>.None(), Optional<DateTime>.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<Updated> result = directory.RemoveItem(item);
// Assert
result.IsError.Should().BeFalse();
directory.Items.Should().NotContain(item);
}
#endregion
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="File"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class FileTests
{
#region ===================================================================== METHODS ===================================================================================
[Fact]
public void Create_WhenCalledWithValidParameters_ShouldReturnSuccessfulResult()
{
// Arrange
string path = "/valid/path/file.txt";
string name = "file.txt";
Optional<DateTime> dateCreated = DateTime.Now;
Optional<DateTime> dateModified = DateTime.Now;
long size = 1024;
// Act
ErrorOr<File> 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<DateTime> dateCreated = DateTime.Now;
Optional<DateTime> dateModified = DateTime.Now;
long size = 1024;
// Act
ErrorOr<File> 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<FileSystemPathId> pathIdResult = FileSystemPathId.Create("/valid/path/file.txt");
pathIdResult.IsError.Should().BeFalse();
FileSystemPathId pathId = pathIdResult.Value;
string name = "file.txt";
Optional<DateTime> dateCreated = DateTime.Now;
Optional<DateTime> dateModified = DateTime.Now;
long size = 1024;
// Act
ErrorOr<File> 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<File> fileResult = File.Create("/valid/path/file.txt", "file.txt", Optional<DateTime>.None(), Optional<DateTime>.None(), 1024);
fileResult.IsError.Should().BeFalse();
File file = fileResult.Value;
DateTime newDate = DateTime.Now;
// Act
ErrorOr<Updated> result = file.UpdateLastModified(newDate);
// Assert
result.IsError.Should().BeFalse();
file.DateModified.Value.Should().Be(newDate);
}
[Fact]
public void UpdateSize_WhenCalled_ShouldUpdateFileSize()
{
// Arrange
ErrorOr<File> fileResult = File.Create("/valid/path/file.txt", "file.txt", Optional<DateTime>.None(), Optional<DateTime>.None(), 1024);
fileResult.IsError.Should().BeFalse();
File file = fileResult.Value;
long newSize = 2048;
// Act
ErrorOr<Updated> result = file.UpdateSize(newSize);
// Assert
result.IsError.Should().BeFalse();
file.Size.Should().Be(newSize);
}
[Fact]
public void Rename_WhenCalledWithValidName_ShouldUpdateFileName()
{
// Arrange
ErrorOr<File> fileResult = File.Create("/valid/path/file.txt", "file.txt", Optional<DateTime>.None(), Optional<DateTime>.None(), 1024);
fileResult.IsError.Should().BeFalse();
File file = fileResult.Value;
string newName = "newfile.txt";
// Act
ErrorOr<Updated> result = file.Rename(newName);
// Assert
result.IsError.Should().BeFalse();
file.Name.Should().Be(newName);
}
[Fact]
public void Rename_WhenCalledWithEmptyName_ShouldReturnError()
{
// Arrange
ErrorOr<File> fileResult = File.Create("/valid/path/file.txt", "file.txt", Optional<DateTime>.None(), Optional<DateTime>.None(), 1024);
fileResult.IsError.Should().BeFalse();
File file = fileResult.Value;
string emptyName = "";
// Act
ErrorOr<Updated> result = file.Rename(emptyName);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.FileManagement.NameCannotBeEmpty);
file.Name.Should().Be("file.txt");
}
#endregion
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="Directory"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DirectoryFixture
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly Faker _faker;
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="DirectoryFixture"/> class.
/// </summary>
public DirectoryFixture()
{
_faker = new Faker();
}
#endregion
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Creates a random valid <see cref="Directory"/>.
/// </summary>
/// <param name="path">Optional. The directory path. If not provided, a random path is generated.</param>
/// <param name="name">Optional. The directory name. If not provided, a random name is generated.</param>
/// <param name="dateCreated">Optional. The directory's creation date. If not provided, a random past date is generated.</param>
/// <param name="dateModified">Optional. The directory's modification date. If not provided, a recent date is generated.</param>
/// <param name="status">Optional. The directory's status. If not provided, a random status is assigned.</param>
/// <param name="childItems">Optional. A list of child items to be added to the directory.</param>
/// <returns>A newly created <see cref="Directory"/> instance.</returns>
/// <exception cref="InvalidOperationException">Thrown if the <see cref="Directory"/> creation fails.</exception>
public Directory CreateDirectory(
string? path = null,
string? name = null,
Optional<DateTime>? dateCreated = null,
Optional<DateTime>? dateModified = null,
FileSystemItemStatus? status = null,
List<FileSystemItem>? childItems = null)
{
path ??= _faker.System.FilePath();
name ??= _faker.System.FileName();
dateCreated ??= Optional<DateTime>.Some(_faker.Date.Past());
dateModified ??= Optional<DateTime>.Some(_faker.Date.Recent());
status ??= _faker.PickRandom<FileSystemItemStatus>();
ErrorOr<Directory> 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;
}
/// <summary>
/// Creates a list of <see cref="Directory"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<Directory> CreateMany(int count = 3)
{
return Enumerable.Range(0, count).Select(_ => CreateDirectory()).ToList();
}
/// <summary>
/// Creates a list of nested <see cref="Directory"/> objects with a hierarchical structure.
/// </summary>
/// <param name="count">The number of top-level directories to create. Default is 3.</param>
/// <param name="maxDepth">The maximum depth of the directory hierarchy. Default is 3.</param>
/// <param name="maxChildrenPerDirectory">The maximum number of child items (files or directories) per directory. Default is 3.</param>
/// <returns>A list of <see cref="Directory"/> objects with nested structures.</returns>
public List<Directory> CreateManyNested(int count = 3, int maxDepth = 3, int maxChildrenPerDirectory = 3)
{
return Enumerable.Range(0, count).Select(_ => CreateNestedDirectory(1, maxDepth, maxChildrenPerDirectory)).ToList();
}
/// <summary>
/// Recursively creates a nested <see cref="Directory"/> structure.
/// </summary>
/// <param name="currentDepth">The current depth in the directory hierarchy.</param>
/// <param name="maxDepth">The maximum allowed depth for the directory hierarchy.</param>
/// <param name="maxChildrenPerDirectory">The maximum number of child items (files or directories) allowed per directory.</param>
/// <returns>A <see cref="Directory"/> object that may contain nested directories and files.</returns>
private Directory CreateNestedDirectory(int currentDepth, int maxDepth, int maxChildrenPerDirectory)
{
List<FileSystemItem> 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
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="File"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class FileFixture
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly Faker _faker;
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="FileFixture"/> class.
/// </summary>
public FileFixture()
{
_faker = new Faker();
}
#endregion
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Creates a random valid <see cref="File"/>.
/// </summary>
/// <returns>The created <see cref="File"/>.</returns>
public File CreateFile(
string? path = null,
string? name = null,
Optional<DateTime>? dateCreated = null,
Optional<DateTime>? dateModified = null,
long? size = null,
FileSystemItemStatus? status = null)
{
path ??= _faker.System.FilePath();
name ??= _faker.System.FileName();
dateCreated ??= Optional<DateTime>.Some(_faker.Date.Past());
dateModified ??= Optional<DateTime>.Some(_faker.Date.Recent());
size ??= _faker.Random.Long();
status ??= _faker.PickRandom<FileSystemItemStatus>();
ErrorOr<File> 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;
}
/// <summary>
/// Creates a list of <see cref="File"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<File> CreateMany(int count = 3)
{
return Enumerable.Range(0, count).Select(_ => CreateFile()).ToList();
}
/// <summary>
/// Creates a random valid <see cref="File"/>, without creationg and modification dates.
/// </summary>
/// <returns></returns>
public static File CreateFileWithoutDates()
{
return File.Create(
"/path/to/file_without_dates.txt",
"file_without_dates.txt",
Optional<DateTime>.None(),
Optional<DateTime>.None(),
2048,
FileSystemItemStatus.Accessible
).Value;
}
#endregion
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="UnixRootItem"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UnixRootItemFixture
{
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Creates a random valid <see cref="UnixRootItem"/>.
/// </summary>
/// <param name="status">The status of the UNIX root item.</param>
/// <returns>The created <see cref="UnixRootItem"/>.</returns>
public UnixRootItem CreateUnixRootItem(FileSystemItemStatus status = FileSystemItemStatus.Accessible)
{
ErrorOr<UnixRootItem> unixRootItemResult = UnixRootItem.Create(status);
if (unixRootItemResult.IsError)
throw new InvalidOperationException("Failed to create UnixRootItem: " + string.Join(", ", unixRootItemResult.Errors));
return unixRootItemResult.Value;
}
#endregion
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="UnixRootItem"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UnixRootItemTests
{
#region ===================================================================== METHODS ===================================================================================
[Fact]
public void Create_WhenCalledWithDefaultStatus_ShouldReturnSuccessfulResult()
{
// Arrange & Act
ErrorOr<UnixRootItem> 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<UnixRootItem> 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<UnixRootItem> createResult = UnixRootItem.Create();
createResult.IsError.Should().BeFalse();
UnixRootItem unixRootItem = createResult.Value;
// Act
IReadOnlyCollection<FileSystemItem> items = unixRootItem.Items;
// Assert
items.Should().BeEmpty();
items.Should().BeAssignableTo<IReadOnlyCollection<FileSystemItem>>();
}
[Fact]
public void SetStatus_WhenCalledWithNewStatus_ShouldUpdateStatus()
{
// Arrange
ErrorOr<UnixRootItem> createResult = UnixRootItem.Create();
createResult.IsError.Should().BeFalse();
UnixRootItem unixRootItem = createResult.Value;
FileSystemItemStatus newStatus = FileSystemItemStatus.Accessible;
// Act
ErrorOr<Updated> result = unixRootItem.SetStatus(newStatus);
// Assert
result.IsError.Should().BeFalse();
unixRootItem.Status.Should().Be(newStatus);
}
[Fact]
public void SetParent_WhenCalledWithNullParent_ShouldReturnError()
{
// Arrange
ErrorOr<UnixRootItem> createResult = UnixRootItem.Create();
createResult.IsError.Should().BeFalse();
UnixRootItem unixRootItem = createResult.Value;
// Act
ErrorOr<Updated> result = unixRootItem.SetParent(null!);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.FileManagement.ParentNodeCannotBeNull);
unixRootItem.Parent.HasValue.Should().BeFalse();
}
#endregion
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="WindowsRootItem"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class WindowsRootItemTests
{
#region ===================================================================== METHODS ===================================================================================
[Fact]
public void Create_WhenCalledWithValidParameters_ShouldReturnSuccessfulResult()
{
// Arrange
string path = "C:\\";
string name = "C:";
// Act
ErrorOr<WindowsRootItem> 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<WindowsRootItem> 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<WindowsRootItem> 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<FileSystemPathId> pathIdResult = FileSystemPathId.Create("E:\\");
pathIdResult.IsError.Should().BeFalse();
FileSystemPathId pathId = pathIdResult.Value;
string name = "E:";
// Act
ErrorOr<WindowsRootItem> 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<WindowsRootItem> createResult = WindowsRootItem.Create("F:\\", "F:");
createResult.IsError.Should().BeFalse();
WindowsRootItem windowsRootItem = createResult.Value;
// Act
IReadOnlyCollection<FileSystemItem> items = windowsRootItem.Items;
// Assert
items.Should().BeEmpty();
items.Should().BeAssignableTo<IReadOnlyCollection<FileSystemItem>>();
}
[Fact]
public void SetStatus_WhenCalledWithNewStatus_ShouldUpdateStatus()
{
// Arrange
ErrorOr<WindowsRootItem> createResult = WindowsRootItem.Create("G:\\", "G:");
createResult.IsError.Should().BeFalse();
WindowsRootItem windowsRootItem = createResult.Value;
FileSystemItemStatus newStatus = FileSystemItemStatus.Accessible;
// Act
ErrorOr<Updated> result = windowsRootItem.SetStatus(newStatus);
// Assert
result.IsError.Should().BeFalse();
windowsRootItem.Status.Should().Be(newStatus);
}
[Fact]
public void SetParent_WhenCalledWithNullParent_ShouldReturnError()
{
// Arrange
ErrorOr<WindowsRootItem> createResult = WindowsRootItem.Create("H:\\", "H:");
createResult.IsError.Should().BeFalse();
WindowsRootItem windowsRootItem = createResult.Value;
// Act
ErrorOr<Updated> result = windowsRootItem.SetParent(null!);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.FileManagement.ParentNodeCannotBeNull);
windowsRootItem.Parent.HasValue.Should().BeFalse();
}
#endregion
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="FileSystemItem"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class FileSystemItemTests
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly IFixture _fixture;
private readonly FileSystemPathIdFixture _fileSystemPathIdFixture;
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="FileSystemItemTests"/> class.
/// </summary>
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<FileSystemItem>.None());
}
[Fact]
public void SetStatus_WhenCalled_ShouldUpdateStatusAndReturnUpdated()
{
// Arrange
FileSystemItemFixture item = CreateFileSystemItemFixture();
FileSystemItemStatus newStatus = FileSystemItemStatus.Inaccessible;
// Act
ErrorOr<Updated> 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<Updated> result = item.SetParent(parent);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().Be(Result.Updated);
item.Parent.Should().Be(Optional<FileSystemItem>.Some(parent));
}
[Fact]
public void SetParent_WithNullParent_ShouldReturnError()
{
// Arrange
FileSystemItemFixture item = CreateFileSystemItemFixture();
// Act
ErrorOr<Updated> result = item.SetParent(null!);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.FileManagement.ParentNodeCannotBeNull);
item.Parent.Should().Be(Optional<FileSystemItem>.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<string>();
FileSystemItemType type = _fixture.Create<FileSystemItemType>();
return new FileSystemItemFixture(id, name, type);
}
#endregion
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="FileSystemItem"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class FileSystemItemFixture : FileSystemItem
{
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="FileSystemItemFixture"/> class.
/// </summary>
/// <param name="id">The unique identifier for the file system path.</param>
/// <param name="name">The name of the file system item.</param>
/// <param name="fileSystemItemType">The type of the file system item.</param>
public FileSystemItemFixture(FileSystemPathId id, string name, FileSystemItemType fileSystemItemType)
: base(id, name, fileSystemItemType)
{
}
#endregion
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="DirectoryService"/> class.
/// </summary>
[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 =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="DirectoryServiceTests"/> class.
/// </summary>
public DirectoryServiceTests()
{
_mockEnvironmentContext = Substitute.For<IEnvironmentContext>();
_mockPlatformContextManager = Substitute.For<IPlatformContextManager>();
_mockPlatformContext = Substitute.For<IPlatformContext>();
_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<DateTime>.FromNullable(DateTime.Now)));
_mockEnvironmentContext.DirectoryProviderService.GetCreationTime(subPath)
.Returns(ErrorOrFactory.From(Optional<DateTime>.FromNullable(DateTime.Now.AddDays(-1))));
}
// Act
ErrorOr<IEnumerable<Directory>> 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<IEnumerable<Directory>> 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<IEnumerable<Directory>> 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<IEnumerable<Directory>> 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<DateTime>.FromNullable(DateTime.Now)));
_mockEnvironmentContext.DirectoryProviderService.GetCreationTime(subPath)
.Returns(ErrorOrFactory.From(Optional<DateTime>.FromNullable(DateTime.Now.AddDays(-1))));
}
// Act
ErrorOr<IEnumerable<Directory>> 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<IEnumerable<Directory>> 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<IEnumerable<Directory>> 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<DateTime>.FromNullable(DateTime.Now)));
_mockEnvironmentContext.DirectoryProviderService.GetCreationTime(subPath)
.Returns(ErrorOrFactory.From(Optional<DateTime>.FromNullable(DateTime.Now.AddDays(-1))));
}
// Act
ErrorOr<IEnumerable<Directory>> 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<IEnumerable<Directory>> 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<IEnumerable<Directory>> result = _sut.GetSubdirectories(pathId, includeHiddenElements);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().HaveCount(1);
result.Value.First().Status.Should().Be(FileSystemItemStatus.Inaccessible);
}
[Fact]
public void CreateDirectory_WithValidStringPath_ShouldReturnNewDirectory()
{
// Arrange
string parentPath = _pathDirTest;
string newDirName = "NewDirectory";
FileSystemPathId parentPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(parentPath);
FileSystemPathId newDirPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(System.IO.Path.Combine(parentPath, newDirName));
_mockEnvironmentContext.DirectoryProviderService.CreateDirectory(parentPathId, newDirName)
.Returns(ErrorOrFactory.From(newDirPathId));
_mockEnvironmentContext.DirectoryProviderService.GetFileName(newDirPathId)
.Returns(ErrorOrFactory.From(newDirName));
_mockEnvironmentContext.DirectoryProviderService.GetLastWriteTime(newDirPathId)
.Returns(ErrorOrFactory.From(Optional<DateTime>.FromNullable(DateTime.Now)));
_mockEnvironmentContext.DirectoryProviderService.GetCreationTime(newDirPathId)
.Returns(ErrorOrFactory.From(Optional<DateTime>.FromNullable(DateTime.Now)));
// Act
ErrorOr<Directory> result = _sut.CreateDirectory(parentPath, newDirName);
// Assert
result.IsError.Should().BeFalse();
result.Value.Id.Should().Be(newDirPathId);
}
[Fact]
public void CreateDirectory_WithInvalidStringPath_ShouldReturnError()
{
// Arrange
string invalidPath = string.Empty;
string newDirName = "NewDirectory";
// Act
ErrorOr<Directory> result = _sut.CreateDirectory(invalidPath, newDirName);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.FileManagement.InvalidPath);
}
[Fact]
public void CreateDirectory_WithFileSystemPathId_ShouldReturnNewDirectory()
{
// Arrange
FileSystemPathId parentPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDirTest);
string newDirName = "NewDirectory";
FileSystemPathId newDirPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(System.IO.Path.Combine(parentPathId.Path, newDirName));
_mockEnvironmentContext.DirectoryProviderService.CreateDirectory(parentPathId, newDirName)
.Returns(ErrorOrFactory.From(newDirPathId));
_mockEnvironmentContext.DirectoryProviderService.GetFileName(newDirPathId)
.Returns(ErrorOrFactory.From(newDirName));
_mockEnvironmentContext.DirectoryProviderService.GetLastWriteTime(newDirPathId)
.Returns(ErrorOrFactory.From(Optional<DateTime>.FromNullable(DateTime.Now)));
_mockEnvironmentContext.DirectoryProviderService.GetCreationTime(newDirPathId)
.Returns(ErrorOrFactory.From(Optional<DateTime>.FromNullable(DateTime.Now)));
// Act
ErrorOr<Directory> result = _sut.CreateDirectory(parentPathId, newDirName);
// Assert
result.IsError.Should().BeFalse();
result.Value.Id.Should().Be(newDirPathId);
}
[Fact]
public void CreateDirectory_WhenDirectoryProviderServiceReturnsError_ShouldPropagateError()
{
// Arrange
FileSystemPathId parentPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDirTest);
string newDirName = "NewDirectory";
_mockEnvironmentContext.DirectoryProviderService.CreateDirectory(parentPathId, newDirName)
.Returns(Errors.Permission.UnauthorizedAccess);
// Act
ErrorOr<Directory> result = _sut.CreateDirectory(parentPathId, newDirName);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess);
}
[Fact]
public void CreateDirectory_WhenDirectoryDetailsAreInaccessible_ShouldReturnInaccessibleDirectory()
{
// Arrange
FileSystemPathId parentPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDirTest);
string newDirName = "NewDirectory";
FileSystemPathId newDirPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(System.IO.Path.Combine(parentPathId.Path, newDirName));
_mockEnvironmentContext.DirectoryProviderService.CreateDirectory(parentPathId, newDirName)
.Returns(ErrorOrFactory.From(newDirPathId));
_mockEnvironmentContext.DirectoryProviderService.GetFileName(newDirPathId)
.Returns(Errors.Permission.UnauthorizedAccess);
_mockEnvironmentContext.DirectoryProviderService.GetLastWriteTime(newDirPathId)
.Returns(Errors.Permission.UnauthorizedAccess);
_mockEnvironmentContext.DirectoryProviderService.GetCreationTime(newDirPathId)
.Returns(Errors.Permission.UnauthorizedAccess);
// Act
ErrorOr<Directory> result = _sut.CreateDirectory(parentPathId, newDirName);
// Assert
result.IsError.Should().BeFalse();
result.Value.Status.Should().Be(FileSystemItemStatus.Inaccessible);
result.Value.Id.Should().Be(newDirPathId);
result.Value.DateCreated.HasValue.Should().BeFalse();
result.Value.DateModified.HasValue.Should().BeFalse();
}
[Fact]
public void CreateDirectory_WhenDirectoryExistsReturnsError_ShouldPropagateError()
{
// Arrange
FileSystemPathId parentPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDirTest);
string newDirName = "NewDirectory";
FileSystemPathId newDirPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(System.IO.Path.Combine(parentPathId.Path, newDirName));
_mockPlatformContext.PathStrategy.CombinePath(parentPathId, newDirName).Returns(ErrorOrFactory.From(newDirPathId));
_mockEnvironmentContext.DirectoryProviderService.DirectoryExists(newDirPathId)
.Returns(Errors.Permission.UnauthorizedAccess);
// Act
ErrorOr<Directory> result = _sut.CreateDirectory(parentPathId, newDirName);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess);
}
[Fact]
public void CreateDirectory_WhenDirectoryAlreadyExists_ShouldReturnDirectoryAlreadyExistsError()
{
// Arrange
FileSystemPathId parentPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDirTest);
string newDirName = "ExistingDirectory";
FileSystemPathId newDirPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(System.IO.Path.Combine(parentPathId.Path, newDirName));
_mockPlatformContext.PathStrategy.CombinePath(parentPathId, newDirName).Returns(ErrorOrFactory.From(newDirPathId));
_mockEnvironmentContext.DirectoryProviderService.DirectoryExists(newDirPathId).Returns(true);
// Act
ErrorOr<Directory> result = _sut.CreateDirectory(parentPathId, newDirName);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.FileManagement.DirectoryAlreadyExists);
}
[Fact]
public void CreateDirectory_WhenCombinePathReturnsError_ShouldReturnError()
{
// Arrange
FileSystemPathId parentPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDirTest);
string newDirName = "NewDirectory";
_mockPlatformContext.PathStrategy.CombinePath(parentPathId, newDirName)
.Returns(Errors.FileManagement.InvalidPath);
// Act
ErrorOr<Directory> result = _sut.CreateDirectory(parentPathId, newDirName);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.FileManagement.InvalidPath);
// Verify that DirectoryExists was not called
_mockEnvironmentContext.DirectoryProviderService.DidNotReceive().DirectoryExists(Arg.Any<FileSystemPathId>());
_mockEnvironmentContext.DirectoryProviderService.DidNotReceive().CreateDirectory(Arg.Any<FileSystemPathId>(), Arg.Any<string>());
}
[Fact]
public void RenameDirectory_WithValidStringPath_ShouldReturnRenamedDirectory()
{
// Arrange
string oldPath = s_isLinux ? "/TestDir/OldName" : @"C:\TestDir\OldName";
string newName = "NewName";
FileSystemPathId oldPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(oldPath);
FileSystemPathId newPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(
s_isLinux ? "/TestDir/NewName" : @"C:\TestDir\NewName"
);
_mockEnvironmentContext.DirectoryProviderService.RenameDirectory(oldPathId, newName)
.Returns(ErrorOrFactory.From(newPathId));
_mockEnvironmentContext.DirectoryProviderService.GetFileName(newPathId)
.Returns(ErrorOrFactory.From(newName));
_mockEnvironmentContext.DirectoryProviderService.GetLastWriteTime(newPathId)
.Returns(ErrorOrFactory.From(Optional<DateTime>.FromNullable(DateTime.Now)));
_mockEnvironmentContext.DirectoryProviderService.GetCreationTime(newPathId)
.Returns(ErrorOrFactory.From(Optional<DateTime>.FromNullable(DateTime.Now)));
// Act
ErrorOr<Directory> result = _sut.RenameDirectory(oldPath, newName);
// Assert
result.IsError.Should().BeFalse();
result.Value.Id.Should().Be(newPathId);
result.Value.Name.Should().Be(newName);
}
[Fact]
public void RenameDirectory_WithInvalidStringPath_ShouldReturnError()
{
// Arrange
string invalidPath = string.Empty;
string newName = "NewName";
// Act
ErrorOr<Directory> result = _sut.RenameDirectory(invalidPath, newName);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.FileManagement.InvalidPath);
}
[Fact]
public void RenameDirectory_WithFileSystemPathId_ShouldReturnRenamedDirectory()
{
// Arrange
FileSystemPathId oldPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(
s_isLinux ? "/TestDir/OldName" : @"C:\TestDir\OldName"
);
string newName = "NewName";
FileSystemPathId newPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(
s_isLinux ? "/TestDir/NewName" : @"C:\TestDir\NewName"
);
_mockEnvironmentContext.DirectoryProviderService.RenameDirectory(oldPathId, newName)
.Returns(ErrorOrFactory.From(newPathId));
_mockEnvironmentContext.DirectoryProviderService.GetFileName(newPathId)
.Returns(ErrorOrFactory.From(newName));
_mockEnvironmentContext.DirectoryProviderService.GetLastWriteTime(newPathId)
.Returns(ErrorOrFactory.From(Optional<DateTime>.FromNullable(DateTime.Now)));
_mockEnvironmentContext.DirectoryProviderService.GetCreationTime(newPathId)
.Returns(ErrorOrFactory.From(Optional<DateTime>.FromNullable(DateTime.Now)));
// Act
ErrorOr<Directory> result = _sut.RenameDirectory(oldPathId, newName);
// Assert
result.IsError.Should().BeFalse();
result.Value.Id.Should().Be(newPathId);
result.Value.Name.Should().Be(newName);
}
[Fact]
public void RenameDirectory_WhenDirectoryProviderServiceReturnsError_ShouldPropagateError()
{
// Arrange
FileSystemPathId oldPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(
s_isLinux ? "/TestDir/OldName" : @"C:\TestDir\OldName"
);
string newName = "NewName";
_mockEnvironmentContext.DirectoryProviderService.RenameDirectory(oldPathId, newName)
.Returns(Errors.Permission.UnauthorizedAccess);
// Act
ErrorOr<Directory> result = _sut.RenameDirectory(oldPathId, newName);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess);
}
[Fact]
public void RenameDirectory_WhenDirectoryDetailsAreInaccessible_ShouldReturnInaccessibleDirectory()
{
// Arrange
FileSystemPathId oldPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(
s_isLinux ? "/TestDir/OldName" : @"C:\TestDir\OldName"
);
string newName = "NewName";
FileSystemPathId newPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(
s_isLinux ? "/TestDir/NewName" : @"C:\TestDir\NewName"
);
_mockEnvironmentContext.DirectoryProviderService.RenameDirectory(oldPathId, newName)
.Returns(ErrorOrFactory.From(newPathId));
_mockEnvironmentContext.DirectoryProviderService.GetFileName(newPathId)
.Returns(Errors.Permission.UnauthorizedAccess);
_mockEnvironmentContext.DirectoryProviderService.GetLastWriteTime(newPathId)
.Returns(Errors.Permission.UnauthorizedAccess);
_mockEnvironmentContext.DirectoryProviderService.GetCreationTime(newPathId)
.Returns(Errors.Permission.UnauthorizedAccess);
// Act
ErrorOr<Directory> result = _sut.RenameDirectory(oldPathId, newName);
// Assert
result.IsError.Should().BeFalse();
result.Value.Status.Should().Be(FileSystemItemStatus.Inaccessible);
result.Value.Id.Should().Be(newPathId);
result.Value.DateCreated.HasValue.Should().BeFalse();
result.Value.DateModified.HasValue.Should().BeFalse();
}
[Fact]
public void RenameDirectory_WhenDirectoryAlreadyExists_ShouldReturnDirectoryAlreadyExistsError()
{
// Arrange
FileSystemPathId oldPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(
s_isLinux ? "/TestDir/OldName" : @"C:\TestDir\OldName"
);
string newName = "ExistingDirectory";
FileSystemPathId newPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(
s_isLinux ? "/TestDir/ExistingDirectory" : @"C:\TestDir\ExistingDirectory"
);
_mockPlatformContext.PathStrategy.CombinePath(Arg.Any<FileSystemPathId>(), newName)
.Returns(ErrorOrFactory.From(newPathId));
_mockEnvironmentContext.DirectoryProviderService.DirectoryExists(newPathId)
.Returns(ErrorOrFactory.From(true));
// Act
ErrorOr<Directory> result = _sut.RenameDirectory(oldPathId, newName);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.FileManagement.DirectoryAlreadyExists);
}
[Fact]
public void RenameDirectory_WhenCombinePathReturnsError_ShouldReturnError()
{
// Arrange
FileSystemPathId oldPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(
s_isLinux ? "/TestDir/OldName" : @"C:\TestDir\OldName"
);
string newName = "NewName";
_mockPlatformContext.PathStrategy.CombinePath(Arg.Any<FileSystemPathId>(), newName)
.Returns(Errors.FileManagement.InvalidPath);
// Act
ErrorOr<Directory> result = _sut.RenameDirectory(oldPathId, newName);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.FileManagement.InvalidPath);
// Verify that DirectoryExists and RenameDirectory were not called
_mockEnvironmentContext.DirectoryProviderService.DidNotReceive().DirectoryExists(Arg.Any<FileSystemPathId>());
_mockEnvironmentContext.DirectoryProviderService.DidNotReceive().RenameDirectory(Arg.Any<FileSystemPathId>(), Arg.Any<string>());
}
[Fact]
public void RenameDirectory_WhenDirectoryExistsReturnsError_ShouldPropagateError()
{
// Arrange
FileSystemPathId oldPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(
s_isLinux ? "/TestDir/OldName" : @"C:\TestDir\OldName"
);
string newName = "NewName";
FileSystemPathId newPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(
s_isLinux ? "/TestDir/NewName" : @"C:\TestDir\NewName"
);
_mockPlatformContext.PathStrategy.CombinePath(Arg.Any<FileSystemPathId>(), newName)
.Returns(ErrorOrFactory.From(newPathId));
_mockEnvironmentContext.DirectoryProviderService.DirectoryExists(newPathId)
.Returns(Errors.Permission.UnauthorizedAccess);
// Act
ErrorOr<Directory> result = _sut.RenameDirectory(oldPathId, newName);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess);
// Verify that RenameDirectory was not called
_mockEnvironmentContext.DirectoryProviderService.DidNotReceive().RenameDirectory(Arg.Any<FileSystemPathId>(), Arg.Any<string>());
}
[Fact]
public void DeleteDirectory_WithValidStringPath_ShouldReturnDeleted()
{
// Arrange
string path = s_isLinux ? "/TestDir/ToDelete" : @"C:\TestDir\ToDelete";
FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path);
_mockEnvironmentContext.DirectoryProviderService.DeleteDirectory(pathId)
.Returns(Result.Deleted);
// Act
ErrorOr<Deleted> result = _sut.DeleteDirectory(path);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().Be(Result.Deleted);
}
[Fact]
public void DeleteDirectory_WithInvalidStringPath_ShouldReturnError()
{
// Arrange
string invalidPath = string.Empty;
// Act
ErrorOr<Deleted> result = _sut.DeleteDirectory(invalidPath);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.FileManagement.InvalidPath);
}
[Fact]
public void DeleteDirectory_WithFileSystemPathId_ShouldReturnDeleted()
{
// Arrange
FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(
s_isLinux ? "/TestDir/ToDelete" : @"C:\TestDir\ToDelete"
);
_mockEnvironmentContext.DirectoryProviderService.DeleteDirectory(pathId)
.Returns(Result.Deleted);
// Act
ErrorOr<Deleted> result = _sut.DeleteDirectory(pathId);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().Be(Result.Deleted);
}
[Fact]
public void DeleteDirectory_WhenDirectoryProviderServiceReturnsError_ShouldPropagateError()
{
// Arrange
FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(
s_isLinux ? "/TestDir/ToDelete" : @"C:\TestDir\ToDelete"
);
_mockEnvironmentContext.DirectoryProviderService.DeleteDirectory(pathId)
.Returns(Errors.Permission.UnauthorizedAccess);
// Act
ErrorOr<Deleted> result = _sut.DeleteDirectory(pathId);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess);
}
[Fact]
public void DeleteDirectory_WhenDirectoryDoesNotExist_ShouldReturnDirectoryNotFoundError()
{
// Arrange
FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(
s_isLinux ? "/TestDir/NonExistent" : @"C:\TestDir\NonExistent"
);
_mockEnvironmentContext.DirectoryProviderService.DeleteDirectory(pathId)
.Returns(Errors.FileManagement.DirectoryNotFound);
// Act
ErrorOr<Deleted> result = _sut.DeleteDirectory(pathId);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.FileManagement.DirectoryNotFound);
}
#endregion
}
@@ -0,0 +1,94 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FluentAssertions;
using Lumina.Contracts.Enums.FileSystem;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform;
using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Fixtures;
using NSubstitute;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO.Abstractions;
using System.Linq;
#endregion
namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Services;
/// <summary>
/// Contains unit tests for the <see cref="DriveService"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DriveServiceTests
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly IFileSystem _mockFileSystem;
private readonly IPlatformContextManager _mockPlatformContextManager;
private readonly IPlatformContext _mockPlatformContext;
private readonly DriveService _sut;
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="DriveServiceTests"/> class.
/// </summary>
public DriveServiceTests()
{
_mockFileSystem = Substitute.For<IFileSystem>();
_mockPlatformContextManager = Substitute.For<IPlatformContextManager>();
_mockPlatformContext = Substitute.For<IPlatformContext>();
_mockPlatformContextManager.GetCurrentContext().Returns(_mockPlatformContext);
_sut = new DriveService(_mockFileSystem, _mockPlatformContextManager);
}
#endregion
#region ===================================================================== METHODS ===================================================================================
[Fact]
public void GetDrives_OnUnixPlatform_ShouldReturnSingleUnixRootItem()
{
// Arrange
_mockPlatformContext.Platform.Returns(PlatformType.Unix);
// Act
ErrorOr<IEnumerable<FileSystemItem>> result = _sut.GetDrives();
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().HaveCount(1);
result.Value.First().Should().BeOfType<UnixRootItem>();
result.Value.First().Status.Should().Be(FileSystemItemStatus.Accessible);
}
[Fact]
public void GetDrives_OnWindowsPlatform_ShouldReturnWindowsRootItems()
{
// Arrange
_mockPlatformContext.Platform.Returns(PlatformType.Windows);
IDriveInfo[] mockDrives =
[
CreateMockDriveInfo("C:\\", true),
CreateMockDriveInfo("D:\\", true),
CreateMockDriveInfo("E:\\", false) // Not ready
];
_mockFileSystem.DriveInfo.GetDrives().Returns(mockDrives);
// Act
ErrorOr<IEnumerable<FileSystemItem>> result = _sut.GetDrives();
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().HaveCount(2); // Only ready drives
result.Value.Should().AllBeOfType<WindowsRootItem>();
result.Value.Select(d => d.Name).Should().BeEquivalentTo("C:\\", "D:\\");
}
private static IDriveInfo CreateMockDriveInfo(string name, bool isReady)
{
IDriveInfo mockDriveInfo = Substitute.For<IDriveInfo>();
mockDriveInfo.Name.Returns(name);
mockDriveInfo.IsReady.Returns(isReady);
return mockDriveInfo;
}
#endregion
}
@@ -0,0 +1,935 @@
#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;
#endregion
namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Services;
/// <summary>
/// Contains unit tests for the <see cref="FileProviderService"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class FileProviderServiceTests
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly IFixture _fixture;
private readonly IFileSystem _mockFileSystem;
private readonly IFileSystemPermissionsService _mockFileSystemPermissionsService;
private readonly FileProviderService _sut;
private readonly FileSystemPathIdFixture _fileSystemPathIdFixture;
private static readonly bool s_isLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
private readonly string _pathDirTest = s_isLinux ? "/TestDir" : @"C:\TestDir";
private readonly string _pathVisible1 = s_isLinux ? "/Visible.txt" : @"C:\Visible.txt";
private readonly string _pathHidden1 = s_isLinux ? "/Hidden.txt" : @"C:\Hidden.txt";
private readonly string _pathValid1 = s_isLinux ? "/Valid.txt" : @"C:\Valid.txt";
private readonly string _pathInvalid1 = s_isLinux ? "/Invalid.txt" : @"C:\Invalid.txt";
private readonly string _pathSourceFile = s_isLinux ? "/Source/file.txt" : @"C:\Source\file.txt";
private readonly string _pathDestinationFile = s_isLinux ? "/Destination/file.txt" : @"C:\Destination\file.txt";
private readonly string _pathSource = s_isLinux ? "/Source" : @"C:\Source";
private readonly string _pathDestination = s_isLinux ? "/Destination" : @"C:\Destination";
private readonly char _dirSeparator = s_isLinux ? '/' : '\\';
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="FileProviderServiceTests"/> class.
/// </summary>
public FileProviderServiceTests()
{
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
_mockFileSystem = Substitute.For<IFileSystem>();
_mockFileSystemPermissionsService = Substitute.For<IFileSystemPermissionsService>();
_sut = new FileProviderService(_mockFileSystem, _mockFileSystemPermissionsService);
_fileSystemPathIdFixture = new();
}
#endregion
#region ===================================================================== METHODS ===================================================================================
[Fact]
public void GetFilePaths_WhenUserHasNoAccess_ShouldReturnUnauthorizedAccessError()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId();
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory).Returns(false);
// Act
ErrorOr<IEnumerable<FileSystemPathId>> result = _sut.GetFilePaths(path, false);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess);
}
[Fact]
public void GetFilePaths_WhenUserHasAccess_ShouldReturnFiles()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId();
string[] files = _fixture.CreateMany<string>(3).ToArray();
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory).Returns(true);
_mockFileSystem.Directory.GetFiles(path.Path).Returns(files);
// Act
ErrorOr<IEnumerable<FileSystemPathId>> result = _sut.GetFilePaths(path, false);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().HaveCount(3);
result.Value.Select(x => x.Path).Should().BeEquivalentTo(files);
}
[Fact]
public void GetFilePaths_WhenIncludeHiddenElementsIsFalse_ShouldExcludeHiddenFiles()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId();
string[] files = [_pathVisible1, _pathHidden1];
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory).Returns(true);
_mockFileSystem.Directory.GetFiles(path.Path).Returns(files);
_mockFileSystem.File.GetAttributes(_pathVisible1).Returns(FileAttributes.Normal);
_mockFileSystem.File.GetAttributes(_pathHidden1).Returns(FileAttributes.Hidden);
// Act
ErrorOr<IEnumerable<FileSystemPathId>> result = _sut.GetFilePaths(path, false);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().HaveCount(1);
result.Value.First().Path.Should().Be(_pathVisible1);
}
[Fact]
public void GetFilePaths_WhenIncludeHiddenElementsIsTrue_ShouldIncludeHiddenFiles()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId();
string[] files = [_pathVisible1, _pathHidden1];
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory).Returns(true);
_mockFileSystem.Directory.GetFiles(path.Path).Returns(files);
_mockFileSystem.File.GetAttributes(_pathVisible1).Returns(FileAttributes.Normal);
_mockFileSystem.File.GetAttributes(_pathHidden1).Returns(FileAttributes.Hidden);
// Act
ErrorOr<IEnumerable<FileSystemPathId>> result = _sut.GetFilePaths(path, true);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().HaveCount(2);
result.Value.Select(x => x.Path).Should().BeEquivalentTo([_pathVisible1, _pathHidden1]);
}
[Fact]
public void GetFilePaths_WhenGetAttributesThrowsException_ShouldStillAddFile()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId();
string[] files = [_pathValid1, _pathInvalid1];
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory).Returns(true);
_mockFileSystem.Directory.GetFiles(path.Path).Returns(files);
_mockFileSystem.File.GetAttributes(_pathValid1).Returns(FileAttributes.Normal);
_mockFileSystem.File.GetAttributes(_pathInvalid1).Throws(new Exception("Access denied"));
// Act
ErrorOr<IEnumerable<FileSystemPathId>> result = _sut.GetFilePaths(path, false);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().HaveCount(2);
result.Value.Select(x => x.Path).Should().BeEquivalentTo([_pathInvalid1, _pathValid1]);
}
[Fact]
public void GetFilePaths_WhenCalled_ShouldOrderFilesAlphabetically()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId();
string[] files = s_isLinux
? ["/C.txt", "/A.txt", "/B.txt"]
: [@"C:\C.txt", @"C:\A.txt", @"C:\B.txt"];
string[] expectedFiles = s_isLinux
? ["/A.txt", "/B.txt", "/C.txt"]
: [@"C:\A.txt", @"C:\B.txt", @"C:\C.txt"];
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory).Returns(true);
_mockFileSystem.Directory.GetFiles(path.Path).Returns(files);
_mockFileSystem.File.GetAttributes(Arg.Any<string>()).Returns(FileAttributes.Normal);
// Act
ErrorOr<IEnumerable<FileSystemPathId>> result = _sut.GetFilePaths(path, false);
// Assert
result.IsError.Should().BeFalse();
result.Value.Select(x => x.Path).Should().BeEquivalentTo(expectedFiles, options => options.WithStrictOrdering());
}
[Fact]
public void GetFilePaths_WhenDirectoryHasNoFiles_ShouldReturnEmptyList()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId();
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory).Returns(true);
_mockFileSystem.Directory.GetFiles(path.Path).Returns([]);
// Act
ErrorOr<IEnumerable<FileSystemPathId>> result = _sut.GetFilePaths(path, false);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeEmpty();
}
[Fact]
public void FileExists_WhenFileExists_ShouldReturnTrue()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId();
_mockFileSystem.File.Exists(path.Path).Returns(true);
// Act
ErrorOr<bool> result = _sut.FileExists(path);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeTrue();
}
[Fact]
public void FileExists_WhenFileDoesNotExist_ShouldReturnFalse()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId();
_mockFileSystem.File.Exists(path.Path).Returns(false);
// Act
ErrorOr<bool> result = _sut.FileExists(path);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeFalse();
}
[Fact]
public void GetFileName_WhenPathIsValid_ShouldReturnFileName()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId();
string expectedFileName = "testfile.txt";
_mockFileSystem.Path.GetFileName(path.Path).Returns(expectedFileName);
// Act
ErrorOr<string> result = _sut.GetFileName(path);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().Be(expectedFileName);
}
[Fact]
public void GetFileName_WhenPathIsEmpty_ShouldReturnEmptyString()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId();
_mockFileSystem.Path.GetFileName(path.Path).Returns(string.Empty);
// Act
ErrorOr<string> result = _sut.GetFileName(path);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeEmpty();
}
[Fact]
public void GetFileAsync_WhenUserHasAccess_ShouldReturnFileContents()
{
// Arrange
string tempFilePath = Path.GetTempFileName();
try
{
byte[] expectedContents = [1, 2, 3, 4, 5];
File.WriteAllBytes(tempFilePath, expectedContents);
FileSystemPathId path = FileSystemPathId.Create(tempFilePath).Value;
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadContents).Returns(true);
// We need to update the _fileSystem mock to use the real file system for this method
_mockFileSystem.File.ReadAllBytes(tempFilePath).Returns(x => File.ReadAllBytes(x.Arg<string>()));
// Act
ErrorOr<byte[]> result = _sut.GetFileAsync(path);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeEquivalentTo(expectedContents);
}
finally
{
// Clean up
File.Delete(tempFilePath);
}
}
[Fact]
public void GetFileAsync_WhenUserHasNoAccess_ShouldReturnUnauthorizedAccessError()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId();
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadContents).Returns(false);
// Act
ErrorOr<byte[]> result = _sut.GetFileAsync(path);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess);
}
[Fact]
public void GetFileAsync_WhenFileIsEmpty_ShouldReturnEmptyByteArray()
{
// Arrange
string tempFilePath = Path.GetTempFileName();
try
{
FileSystemPathId path = FileSystemPathId.Create(tempFilePath).Value;
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadContents).Returns(true);
// Act
ErrorOr<byte[]> result = _sut.GetFileAsync(path);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeEmpty();
}
finally
{
// Clean up
File.Delete(tempFilePath);
}
}
[Fact]
public void GetLastWriteTime_WhenUserHasAccess_ShouldReturnLastWriteTime()
{
// Arrange
string tempFilePath = Path.GetTempFileName();
try
{
File.WriteAllText(tempFilePath, "Test content");
FileSystemPathId path = FileSystemPathId.Create(tempFilePath).Value;
DateTime expectedDateTime = File.GetLastWriteTime(tempFilePath);
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties).Returns(true);
_mockFileSystem.File.GetLastWriteTime(path.Path).Returns(expectedDateTime);
// Act
ErrorOr<Optional<DateTime>> result = _sut.GetLastWriteTime(path);
// Assert
result.IsError.Should().BeFalse();
result.Value.HasValue.Should().BeTrue();
result.Value.Value.Should().BeCloseTo(expectedDateTime, TimeSpan.FromSeconds(1));
}
finally
{
File.Delete(tempFilePath);
}
}
[Fact]
public void GetLastWriteTime_WhenUserHasNoAccess_ShouldReturnUnauthorizedAccessError()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId();
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties).Returns(false);
// Act
ErrorOr<Optional<DateTime>> result = _sut.GetLastWriteTime(path);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess);
}
[Fact]
public void GetCreationTime_WhenUserHasAccess_ShouldReturnCreationTime()
{
// Arrange
string tempFilePath = Path.GetTempFileName();
try
{
File.WriteAllText(tempFilePath, "Test content");
FileSystemPathId path = FileSystemPathId.Create(tempFilePath).Value;
DateTime expectedDateTime = File.GetCreationTime(tempFilePath);
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties).Returns(true);
_mockFileSystem.File.GetCreationTime(path.Path).Returns(expectedDateTime);
// Act
ErrorOr<Optional<DateTime>> result = _sut.GetCreationTime(path);
// Assert
result.IsError.Should().BeFalse();
result.Value.HasValue.Should().BeTrue();
result.Value.Value.Should().BeCloseTo(expectedDateTime, TimeSpan.FromSeconds(1));
}
finally
{
File.Delete(tempFilePath);
}
}
[Fact]
public void GetCreationTime_WhenUserHasNoAccess_ShouldReturnUnauthorizedAccessError()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId();
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties).Returns(false);
// Act
ErrorOr<Optional<DateTime>> result = _sut.GetCreationTime(path);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess);
}
[Fact]
public void GetSize_WhenUserHasAccess_ShouldReturnFileSize()
{
// Arrange
string tempFilePath = Path.GetTempFileName();
try
{
string content = "Test content";
File.WriteAllText(tempFilePath, content);
FileSystemPathId path = FileSystemPathId.Create(tempFilePath).Value;
long expectedSize = new FileInfo(tempFilePath).Length;
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties).Returns(true);
_mockFileSystem.FileInfo.New(path.Path).Returns(new FileInfoWrapper(_mockFileSystem, new FileInfo(tempFilePath)));
// Act
ErrorOr<long?> result = _sut.GetSize(path);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().NotBeNull();
result.Value.Should().Be(expectedSize);
}
finally
{
File.Delete(tempFilePath);
}
}
[Fact]
public void GetSize_WhenUserHasNoAccess_ShouldReturnUnauthorizedAccessError()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId();
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties).Returns(false);
// Act
ErrorOr<long?> result = _sut.GetSize(path);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess);
}
[Fact]
public void GetSize_WhenFileDoesNotExist_ShouldReturnZero()
{
// Arrange
string nonExistentFilePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
FileSystemPathId path = FileSystemPathId.Create(nonExistentFilePath).Value;
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties).Returns(true);
_mockFileSystem.FileInfo.New(path.Path).Returns((IFileInfo)null!);
// Act
ErrorOr<long?> result = _sut.GetSize(path);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().Be(0);
}
[Fact]
public void CopyFile_WhenSourceFileExistsAndUserHasAccess_ShouldCopyFileAndReturnPath()
{
// Arrange
FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathSourceFile);
FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestination);
bool overrideExisting = false;
_mockFileSystem.File.Exists(sourcePath.Path).Returns(true);
_mockFileSystem.File.Exists(Path.Combine(destinationPath.Path, "file.txt")).Returns(false);
_mockFileSystem.Path.GetFileName(sourcePath.Path).Returns("file.txt");
_mockFileSystem.Path.Combine(destinationPath.Path, "file.txt").Returns(_pathDestinationFile);
// Act
ErrorOr<FileSystemPathId> result = _sut.CopyFile(sourcePath, destinationPath, overrideExisting);
// Assert
result.IsError.Should().BeFalse();
result.Value.Path.Should().Be(_pathDestinationFile);
_mockFileSystem.File.Received(1).Copy(sourcePath.Path, _pathDestinationFile, overrideExisting);
}
[Fact]
public void CopyFile_WhenSourceFileDoesNotExist_ShouldReturnError()
{
// Arrange
FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId();
FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId();
bool overrideExisting = false;
_mockFileSystem.File.Exists(sourcePath.Path).Returns(false);
// Act
ErrorOr<FileSystemPathId> result = _sut.CopyFile(sourcePath, destinationPath, overrideExisting);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.FileManagement.FileNotFound);
}
[Fact]
public void CopyFile_WhenDestinationFileExistsAndOverrideIsFalse_ShouldReturnFileAlreadyExistsError()
{
// Arrange
FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathSourceFile);
FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestination);
string expectedDestinationFilePath = _pathDestinationFile;
bool overrideExisting = false;
_mockFileSystem.File.Exists(sourcePath.Path).Returns(true);
_mockFileSystem.File.Exists(expectedDestinationFilePath).Returns(true);
_mockFileSystem.Path.GetFileName(sourcePath.Path).Returns("file.txt");
_mockFileSystem.Path.GetDirectoryName(sourcePath.Path).Returns(_pathSource);
_mockFileSystem.Path.Combine(Arg.Any<string>(), Arg.Any<string>())
.Returns(callInfo => Path.Combine(callInfo.ArgAt<string>(0), callInfo.ArgAt<string>(1)));
// Act
ErrorOr<FileSystemPathId> result = _sut.CopyFile(sourcePath, destinationPath, overrideExisting);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.FileManagement.FileAlreadyExists);
_mockFileSystem.File.DidNotReceive().Copy(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>());
}
[Fact]
public void CopyFile_WhenOverrideExistingIsTrue_ShouldOverwriteExistingFile()
{
// Arrange
FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathSourceFile);
FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestination);
bool overrideExisting = true;
_mockFileSystem.File.Exists(sourcePath.Path).Returns(true);
_mockFileSystem.File.Exists(_pathDestinationFile).Returns(true);
_mockFileSystem.Path.GetFileName(sourcePath.Path).Returns("file.txt");
_mockFileSystem.Path.Combine(destinationPath.Path, "file.txt").Returns(_pathDestinationFile);
// Act
ErrorOr<FileSystemPathId> result = _sut.CopyFile(sourcePath, destinationPath, overrideExisting);
// Assert
result.IsError.Should().BeFalse();
result.Value.Path.Should().Be(_pathDestinationFile);
_mockFileSystem.File.Received(1).Copy(sourcePath.Path, _pathDestinationFile, overrideExisting);
}
[Fact]
public void CopyFile_WhenExceptionOccurs_ShouldReturnError()
{
// Arrange
FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId();
FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId();
bool overrideExisting = false;
_mockFileSystem.File.Exists(sourcePath.Path).Returns(true);
_mockFileSystem.File.When(x => x.Copy(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>()))
.Do(x => { throw new Exception("Simulated error"); });
// Act
ErrorOr<FileSystemPathId> result = _sut.CopyFile(sourcePath, destinationPath, overrideExisting);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.FileManagement.FileCopyError);
}
[Fact]
public void CopyFile_WhenCopyingToSameDirectory_ShouldCreateUniqueFileName()
{
// Arrange
string sourceDirectory = _pathSource;
FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId(Path.Combine(sourceDirectory, "file.txt"));
FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(sourceDirectory);
string expectedNewFilePath = Path.Combine(sourceDirectory, "file - Copy (1).txt");
bool overrideExisting = false;
_mockFileSystem.File.Exists(sourcePath.Path).Returns(true);
_mockFileSystem.File.Exists(Path.Combine(sourceDirectory, "file.txt")).Returns(true);
_mockFileSystem.File.Exists(expectedNewFilePath).Returns(false);
_mockFileSystem.Path.GetFileName(sourcePath.Path).Returns("file.txt");
_mockFileSystem.Path.GetDirectoryName(sourcePath.Path).Returns(sourceDirectory);
_mockFileSystem.Path.GetFileNameWithoutExtension(Arg.Any<string>()).Returns(x => Path.GetFileNameWithoutExtension(x.Arg<string>()));
_mockFileSystem.Path.GetExtension(Arg.Any<string>()).Returns(x => Path.GetExtension(x.Arg<string>()));
_mockFileSystem.Path.Combine(Arg.Any<string>(), Arg.Any<string>())
.Returns(callInfo => Path.Combine(callInfo.ArgAt<string>(0), callInfo.ArgAt<string>(1)));
// Simulate the behavior of CreateUniqueFilePath
int copyNumber = 1;
_mockFileSystem.File.Exists(Arg.Any<string>())
.Returns(x => {
string path = x.Arg<string>();
if (path == expectedNewFilePath)
return false;
copyNumber++;
return true;
});
// Act
ErrorOr<FileSystemPathId> result = _sut.CopyFile(sourcePath, destinationPath, overrideExisting);
// Assert
result.IsError.Should().BeFalse();
result.Value.Path.Should().Be(expectedNewFilePath);
_mockFileSystem.File.Received(1).Copy(sourcePath.Path, expectedNewFilePath, overrideExisting);
}
[Fact]
public void MoveFile_WhenSourceFileDoesNotExist_ShouldReturnFileNotFoundError()
{
// Arrange
FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId(
s_isLinux ? "/NonExistentSource.txt" : @"C:\NonExistentSource.txt"
);
FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestination);
bool overrideExisting = false;
_mockFileSystem.File.Exists(sourcePath.Path).Returns(false);
// Act
ErrorOr<FileSystemPathId> result = _sut.MoveFile(sourcePath, destinationPath, overrideExisting);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.FileManagement.FileNotFound);
}
[Fact]
public void MoveFile_WhenDestinationFileDoesNotExist_ShouldPerformSimpleMove()
{
// Arrange
FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathSourceFile);
FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestination);
string destinationFilePath = _pathDestinationFile;
bool overrideExisting = false;
_mockFileSystem.File.Exists(sourcePath.Path).Returns(true);
_mockFileSystem.File.Exists(destinationFilePath).Returns(false);
_mockFileSystem.Path.GetFileName(sourcePath.Path).Returns("file.txt");
_mockFileSystem.Path.Combine(destinationPath.Path, "file.txt").Returns(destinationFilePath);
// Act
ErrorOr<FileSystemPathId> result = _sut.MoveFile(sourcePath, destinationPath, overrideExisting);
// Assert
result.IsError.Should().BeFalse();
result.Value.Path.Should().Be(destinationFilePath);
_mockFileSystem.File.Received(1).Move(sourcePath.Path, destinationFilePath);
}
[Fact]
public void MoveFile_WhenDestinationFileExistsAndOverrideIsTrue_ShouldOverwriteFile()
{
// Arrange
FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathSourceFile);
FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestination);
string destinationFilePath = _pathDestinationFile;
bool overrideExisting = true;
_mockFileSystem.File.Exists(sourcePath.Path).Returns(true);
_mockFileSystem.File.Exists(destinationFilePath).Returns(true);
_mockFileSystem.Path.GetFileName(sourcePath.Path).Returns("file.txt");
_mockFileSystem.Path.Combine(destinationPath.Path, "file.txt").Returns(destinationFilePath);
// Act
ErrorOr<FileSystemPathId> result = _sut.MoveFile(sourcePath, destinationPath, overrideExisting);
// Assert
result.IsError.Should().BeFalse();
result.Value.Path.Should().Be(destinationFilePath);
_mockFileSystem.File.Received(1).Move(sourcePath.Path, destinationFilePath, overrideExisting);
}
[Fact]
public void MoveFile_WhenDestinationFileExistsAndOverrideIsFalse_ShouldReturnFileAlreadyExistsError()
{
// Arrange
FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathSourceFile);
FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestination);
string destinationFilePath = _pathDestinationFile;
bool overrideExisting = false;
_mockFileSystem.File.Exists(sourcePath.Path).Returns(true);
_mockFileSystem.File.Exists(destinationFilePath).Returns(true);
_mockFileSystem.Path.GetFileName(sourcePath.Path).Returns("file.txt");
_mockFileSystem.Path.Combine(destinationPath.Path, "file.txt").Returns(destinationFilePath);
// Act
ErrorOr<FileSystemPathId> result = _sut.MoveFile(sourcePath, destinationPath, overrideExisting);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.FileManagement.FileAlreadyExists);
}
[Fact]
public void MoveFile_WhenExceptionOccurs_ShouldReturnFileMoveError()
{
// Arrange
FileSystemPathId sourcePath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathSourceFile);
FileSystemPathId destinationPath = _fileSystemPathIdFixture.CreateFileSystemPathId(_pathDestination);
string destinationFilePath = _pathDestinationFile;
bool overrideExisting = false;
_mockFileSystem.File.Exists(sourcePath.Path).Returns(true);
_mockFileSystem.File.Exists(destinationFilePath).Returns(false);
_mockFileSystem.Path.GetFileName(sourcePath.Path).Returns("file.txt");
_mockFileSystem.Path.Combine(destinationPath.Path, "file.txt").Returns(destinationFilePath);
_mockFileSystem.File.When(x => x.Move(Arg.Any<string>(), Arg.Any<string>()))
.Do(x => throw new IOException("Simulated IO error"));
// Act
ErrorOr<FileSystemPathId> result = _sut.MoveFile(sourcePath, destinationPath, overrideExisting);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.FileManagement.FileMoveError);
}
[Fact]
public void RenameFile_WhenParentDirectoryIsWritable_ShouldRenameSuccessfully()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(
s_isLinux ? "/OldName.txt" : @"C:\OldName.txt"
);
string newName = "NewName.txt";
string parentPath = s_isLinux ? "/" : @"C:\";
string newPath = s_isLinux ? "/NewName.txt" : @"C:\NewName.txt";
IFileInfo fileInfo = Substitute.For<IFileInfo>();
fileInfo.DirectoryName.Returns(parentPath);
_mockFileSystem.FileInfo.New(path.Path).Returns(fileInfo);
_mockFileSystem.Path.Combine(parentPath, newName).Returns(newPath);
_mockFileSystemPermissionsService.CanAccessPath(Arg.Any<FileSystemPathId>(), FileAccessMode.Write).Returns(true);
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Execute).Returns(true);
// Act
ErrorOr<FileSystemPathId> result = _sut.RenameFile(path, newName);
// Assert
result.IsError.Should().BeFalse();
result.Value.Path.Should().Be(newPath);
_mockFileSystem.File.Received(1).Move(path.Path, newPath);
}
[Fact]
public void RenameFile_WhenParentDirectoryIsNotWritable_ShouldReturnUnauthorizedAccessError()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(
s_isLinux ? "/OldName.txt" : @"C:\OldName.txt"
);
string newName = "NewName.txt";
string parentPath = s_isLinux ? "/" : @"C:\";
string newPath = s_isLinux ? "/NewName.txt" : @"C:\NewName.txt";
IFileInfo fileInfo = Substitute.For<IFileInfo>();
fileInfo.DirectoryName.Returns(parentPath);
_mockFileSystem.FileInfo.New(path.Path).Returns(fileInfo);
_mockFileSystem.Path.Combine(parentPath, newName).Returns(newPath);
_mockFileSystemPermissionsService.CanAccessPath(Arg.Any<FileSystemPathId>(), FileAccessMode.Write).Returns(false);
// Act
ErrorOr<FileSystemPathId> result = _sut.RenameFile(path, newName);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess);
_mockFileSystem.File.DidNotReceive().Move(Arg.Any<string>(), Arg.Any<string>());
}
[Fact]
public void RenameFile_WhenFileIsNotExecutable_ShouldReturnUnauthorizedAccessError()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(
s_isLinux ? "/OldName.txt" : @"C:\OldName.txt"
);
string newName = "NewName.txt";
string parentPath = s_isLinux ? "/" : @"C:\";
string newPath = s_isLinux ? "/NewName.txt" : @"C:\NewName.txt";
IFileInfo fileInfo = Substitute.For<IFileInfo>();
fileInfo.DirectoryName.Returns(parentPath);
_mockFileSystem.FileInfo.New(path.Path).Returns(fileInfo);
_mockFileSystem.Path.Combine(parentPath, newName).Returns(newPath);
_mockFileSystemPermissionsService.CanAccessPath(Arg.Any<FileSystemPathId>(), FileAccessMode.Write).Returns(true);
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Execute).Returns(false);
// Act
ErrorOr<FileSystemPathId> result = _sut.RenameFile(path, newName);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess);
_mockFileSystem.File.DidNotReceive().Move(Arg.Any<string>(), Arg.Any<string>());
}
[Fact]
public void RenameFile_WhenParentDirectoryIsNull_ShouldReturnInvalidPathError()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(
s_isLinux ? "/OldName.txt" : @"C:\OldName.txt"
);
string newName = "NewName.txt";
_mockFileSystem.FileInfo.New(path.Path).Returns((IFileInfo)null!);
// Act
ErrorOr<FileSystemPathId> result = _sut.RenameFile(path, newName);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.FileManagement.CannotNavigateUp);
_mockFileSystem.File.DidNotReceive().Move(Arg.Any<string>(), Arg.Any<string>());
}
[Fact]
public void RenameFile_WhenNewPathIsInvalid_ShouldReturnInvalidPathError()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(
s_isLinux ? "/OldName.txt" : @"C:\OldName.txt"
);
string newName = "NewName.txt";
string parentPath = s_isLinux ? "/" : @"C:\";
IFileInfo fileInfo = Substitute.For<IFileInfo>();
fileInfo.DirectoryName.Returns(parentPath);
_mockFileSystem.FileInfo.New(path.Path).Returns(fileInfo);
_mockFileSystem.Path.Combine(parentPath, newName).Returns((string)null!);
// Act
ErrorOr<FileSystemPathId> result = _sut.RenameFile(path, newName);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.FileManagement.InvalidPath);
_mockFileSystem.File.DidNotReceive().Move(Arg.Any<string>(), Arg.Any<string>());
}
[Fact]
public void RenameFile_WhenParentDirectoryExistsButNotWritable_ShouldReturnUnauthorizedAccessError()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(
s_isLinux ? "/OldName.txt" : @"C:\OldName.txt"
);
string newName = "NewName.txt";
string parentPath = s_isLinux ? "/" : @"C:\";
string newPath = s_isLinux ? "/NewName.txt" : @"C:\NewName.txt";
IFileInfo fileInfo = Substitute.For<IFileInfo>();
fileInfo.DirectoryName.Returns(parentPath);
_mockFileSystem.FileInfo.New(path.Path).Returns(fileInfo);
_mockFileSystem.Path.Combine(parentPath, newName).Returns(newPath);
// Mock successful creation of parent directory FileSystemPathId
ErrorOr<FileSystemPathId> parentDirectoryPathId = FileSystemPathId.Create(parentPath);
_mockFileSystem.Path.GetDirectoryName(path.Path).Returns(parentPath);
// Mock permissions: executable for the file, but not writable for the parent directory
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Execute).Returns(true);
_mockFileSystemPermissionsService.CanAccessPath(Arg.Is<FileSystemPathId>(x => x.Path == parentPath), FileAccessMode.Write).Returns(false);
// Act
ErrorOr<FileSystemPathId> result = _sut.RenameFile(path, newName);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess);
_mockFileSystem.File.DidNotReceive().Move(Arg.Any<string>(), Arg.Any<string>());
}
[Fact]
public void DeleteFile_WhenFileExistsAndHasDeletePermission_ShouldDeleteSuccessfully()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(
s_isLinux ? "/FileToDelete.txt" : @"C:\FileToDelete.txt"
);
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Delete).Returns(true);
_mockFileSystem.File.Exists(path.Path).Returns(true);
// Act
ErrorOr<Deleted> result = _sut.DeleteFile(path);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().Be(Result.Deleted);
_mockFileSystem.File.Received(1).Delete(path.Path);
}
[Fact]
public void DeleteFile_WhenNoDeletePermission_ShouldReturnUnauthorizedAccessError()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(
s_isLinux ? "/FileToDelete.txt" : @"C:\FileToDelete.txt"
);
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Delete).Returns(false);
// Act
ErrorOr<Deleted> result = _sut.DeleteFile(path);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess);
_mockFileSystem.File.DidNotReceive().Delete(Arg.Any<string>());
}
#endregion
}
@@ -0,0 +1,237 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FluentAssertions;
using Lumina.Contracts.Enums.FileSystem;
using Lumina.Contracts.Enums.PhotoLibrary;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects;
using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Entities.Fixtures;
using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects.Fixtures;
using NSubstitute;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO.Abstractions.TestingHelpers;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Services;
/// <summary>
/// Contains unit tests for the <see cref="FileTypeService"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class FileTypeServiceTests
{
#region ================================================================== FIELD MEMBERS ================================================================================
private MockFileSystem _mockFileSystem = null!;
private readonly IFileSystemPermissionsService _mockFileSystemPermissionsService;
private FileTypeService? sut;
private readonly FileSystemPathIdFixture _fileSystemPathIdFixture;
private readonly FileFixture _fileFixture;
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="FileTypeServiceTests"/> class.
/// </summary>
public FileTypeServiceTests()
{
_mockFileSystemPermissionsService = Substitute.For<IFileSystemPermissionsService>();
_fileSystemPathIdFixture = new FileSystemPathIdFixture();
_fileFixture = new FileFixture();
}
#endregion
#region ===================================================================== METHODS ===================================================================================
[Fact]
public async Task GetImageTypeAsync_WithValidFile_ShouldReturnCorrectImageType()
{
// Arrange
File file = _fileFixture.CreateFile();
byte[] pngHeader = [137, 80, 78, 71, 13, 10, 26, 10];
byte[] fileContent = [.. pngHeader, .. Enumerable.Repeat<byte>(0, 100)];
SetupMockFileSystem(file.Id, fileContent);
sut = new FileTypeService(_mockFileSystem, _mockFileSystemPermissionsService);
_mockFileSystemPermissionsService.CanAccessPath(file.Id, FileAccessMode.ReadContents).Returns(true);
// Act
ErrorOr<ImageType> result = await sut.GetImageTypeAsync(file, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().Be(ImageType.PNG);
}
[Fact]
public async Task GetImageTypeAsync_WithUnauthorizedAccess_ShouldReturnError()
{
// Arrange
File file = _fileFixture.CreateFile();
SetupMockFileSystem(file.Id, []);
sut = new FileTypeService(_mockFileSystem, _mockFileSystemPermissionsService);
_mockFileSystemPermissionsService.CanAccessPath(file.Id, FileAccessMode.ReadContents).Returns(false);
// Act
ErrorOr<ImageType> result = await sut.GetImageTypeAsync(file, CancellationToken.None);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess);
}
[Fact]
public async Task GetImageTypeAsync_WithSmallFile_ShouldReturnNone()
{
// Arrange
FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\test.jpg");
byte[] fileContent = [1, 2, 3]; // Less than BUFFER_SIZE
SetupMockFileSystem(pathId, fileContent);
sut = new FileTypeService(_mockFileSystem, _mockFileSystemPermissionsService);
_mockFileSystemPermissionsService.CanAccessPath(pathId, FileAccessMode.ReadContents).Returns(true);
// Act
ErrorOr<ImageType> result = await sut.GetImageTypeAsync(pathId, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().Be(ImageType.None);
}
[Fact]
public async Task GetImageTypeAsync_WithSvgFile_ShouldReturnSvgType()
{
// Arrange
FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\test.svg");
string svgContent = "<svg xmlns=\"http://www.w3.org/2000/svg\"></svg>";
byte[] fileContent = Encoding.UTF8.GetBytes(svgContent);
SetupMockFileSystem(pathId, fileContent);
sut = new FileTypeService(_mockFileSystem, _mockFileSystemPermissionsService);
_mockFileSystemPermissionsService.CanAccessPath(pathId, FileAccessMode.ReadContents).Returns(true);
// Act
ErrorOr<ImageType> result = await sut.GetImageTypeAsync(pathId, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().Be(ImageType.SVG);
}
[Fact]
public async Task GetImageTypeAsync_WithTgaFile_ShouldReturnTgaType()
{
// Arrange
FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\test.tga");
byte[] tgaHeader = new byte[18];
tgaHeader[2] = 2; // Set image type to 2 (uncompressed true-color image)
byte[] fileContent = [.. tgaHeader, .. Enumerable.Repeat<byte>(0, 100)];
SetupMockFileSystem(pathId, fileContent);
sut = new FileTypeService(_mockFileSystem, _mockFileSystemPermissionsService);
_mockFileSystemPermissionsService.CanAccessPath(pathId, FileAccessMode.ReadContents).Returns(true);
// Act
ErrorOr<ImageType> result = await sut.GetImageTypeAsync(pathId, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().Be(ImageType.TGA);
}
[Fact]
public async Task GetImageTypeAsync_WithUnknownImageType_ShouldReturnNone()
{
// Arrange
FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\test.unknown");
byte[] fileContent = Enumerable.Repeat<byte>(0, 100).ToArray();
SetupMockFileSystem(pathId, fileContent);
sut = new FileTypeService(_mockFileSystem, _mockFileSystemPermissionsService);
_mockFileSystemPermissionsService.CanAccessPath(pathId, FileAccessMode.ReadContents).Returns(true);
// Act
ErrorOr<ImageType> result = await sut.GetImageTypeAsync(pathId, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().Be(ImageType.None);
}
private void SetupMockFileSystem(FileSystemPathId pathId, byte[] fileContent)
{
MockFileSystem mockFileSystem = new(new Dictionary<string, MockFileData>
{
{ pathId.Path, new MockFileData(fileContent) }
});
_mockFileSystem = mockFileSystem;
}
[Fact]
public async Task GetImageTypeAsync_WithSvgFileStartingWithXmlDeclaration_ShouldReturnSvgType()
{
// Arrange
FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\test.svg");
string svgContent = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<svg xmlns=\"http://www.w3.org/2000/svg\"></svg>";
byte[] fileContent = Encoding.UTF8.GetBytes(svgContent);
SetupMockFileSystem(pathId, fileContent);
sut = new FileTypeService(_mockFileSystem, _mockFileSystemPermissionsService);
_mockFileSystemPermissionsService.CanAccessPath(pathId, FileAccessMode.ReadContents).Returns(true);
// Act
ErrorOr<ImageType> result = await sut.GetImageTypeAsync(pathId, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().Be(ImageType.SVG);
}
[Theory]
[InlineData(new byte[] { 66, 77 }, ImageType.BMP, "BMP")]
[InlineData(new byte[] { 71, 73, 70 }, ImageType.GIF, "GIF")]
[InlineData(new byte[] { 137, 80, 78, 71 }, ImageType.PNG, "PNG")]
[InlineData(new byte[] { 73, 73, 42 }, ImageType.TIFF, "TIFF (Little Endian)")]
[InlineData(new byte[] { 77, 77, 42 }, ImageType.TIFF, "TIFF (Big Endian)")]
[InlineData(new byte[] { 255, 216, 255, 224 }, ImageType.JPEG, "JPEG")]
[InlineData(new byte[] { 255, 216, 255, 225 }, ImageType.JPEG_CANON, "JPEG (Canon)")]
[InlineData(new byte[] { 255, 216, 255, 226 }, ImageType.JPEG_UNKNOWN, "JPEG (Unknown)")]
[InlineData(new byte[] { 0x00, 0x11, 0x02, 0xFF }, ImageType.PICT, "PICT")]
[InlineData(new byte[] { 0x00, 0x00, 0x01, 0x00 }, ImageType.ICO, "ICO")]
[InlineData(new byte[] { 0x38, 0x42, 0x50, 0x53 }, ImageType.PSD, "PSD")]
[InlineData(new byte[] { 0xFF, 0x4F, 0xFF, 0x51 }, ImageType.JPEG2000, "JPEG 2000")]
[InlineData(new byte[] { 0x00, 0x00, 0x00, 0x0C, 0x6A, 0x70, 0x20, 0x20 }, ImageType.AVIF, "AVIF")]
[InlineData(new byte[] { 0x00, 0x00, 0x00, 0x0C, 0x6A, 0x50, 0x20, 0x20 }, ImageType.JPEG2000, "JPEG 2000 (variant)")]
[InlineData(new byte[] { 0x52, 0x49, 0x46, 0x46, 0x00, 0x00, 0x00, 0x00, 0x57, 0x45, 0x42, 0x50 }, ImageType.WEBP, "WEBP")]
[InlineData(new byte[] { 0x00, 0x00, 0x00, 0x00 }, ImageType.None, "Unknown")]
public async Task GetImageTypeAsync_WithVariousImageTypes_ShouldIdentifyCorrectly(byte[] header, ImageType expectedType, string testName)
{
// Arrange
FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId($@"C:\test.{testName.ToLower()}");
byte[] fileContent = [.. header, .. Enumerable.Repeat<byte>(0, 100)];
SetupMockFileSystem(pathId, fileContent);
sut = new FileTypeService(_mockFileSystem, _mockFileSystemPermissionsService);
_mockFileSystemPermissionsService.CanAccessPath(pathId, FileAccessMode.ReadContents).Returns(true);
// Act
ErrorOr<ImageType> result = await sut.GetImageTypeAsync(pathId, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().Be(expectedType, because: $"the file header matches {testName}");
}
#endregion
}
@@ -0,0 +1,50 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Enums.PhotoLibrary;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats;
using SixLabors.ImageSharp.Formats.Bmp;
using SixLabors.ImageSharp.Formats.Gif;
using SixLabors.ImageSharp.Formats.Jpeg;
using SixLabors.ImageSharp.Formats.Png;
using SixLabors.ImageSharp.PixelFormats;
using System.Diagnostics.CodeAnalysis;
using System.IO;
#endregion
namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Services.Fixtures;
/// <summary>
/// Fixture class for the <see cref="ImageType"/> enum.
/// </summary>
[ExcludeFromCodeCoverage]
public class ImageTypeFixture : TheoryData<ImageType, byte[]>
{
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="ImageTypeFixture"/> class.
/// </summary>
public ImageTypeFixture()
{
Add(ImageType.JPEG, CreateImage(new JpegEncoder()));
Add(ImageType.PNG, CreateImage(new PngEncoder()));
Add(ImageType.BMP, CreateImage(new BmpEncoder()));
Add(ImageType.GIF, CreateImage(new GifEncoder()));
}
#endregion
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Creates a byte array representing a thumbnail fixture.
/// </summary>
/// <param name="encoder">The encoder used for the image.</param>
/// <returns>The byte array of the created image.</returns>
private static byte[] CreateImage(IImageEncoder encoder)
{
using Image<Rgba32> image = new(10, 10);
using MemoryStream ms = new();
image.Save(ms, encoder);
return ms.ToArray();
}
#endregion
}
@@ -0,0 +1,500 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FluentAssertions;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Path;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects;
using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects.Fixtures;
using NSubstitute;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Services;
/// <summary>
/// Contains unit tests for the <see cref="PathService"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class PathServiceTests
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly IPlatformContextManager _mockPlatformContextManager;
private readonly IPlatformContext _mockPlatformContext;
private readonly IPathStrategy _mockPathStrategy;
private readonly PathService _sut;
private readonly FileSystemPathIdFixture _fileSystemPathIdFixture;
private readonly PathSegmentFixture _pathSegmentFixture;
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="PathServiceTests"/> class.
/// </summary>
public PathServiceTests()
{
_mockPlatformContextManager = Substitute.For<IPlatformContextManager>();
_mockPlatformContext = Substitute.For<IPlatformContext>();
_mockPathStrategy = Substitute.For<IPathStrategy>();
_mockPlatformContext.PathStrategy.Returns(_mockPathStrategy);
_mockPlatformContextManager.GetCurrentContext().Returns(_mockPlatformContext);
_sut = new PathService(_mockPlatformContextManager);
_fileSystemPathIdFixture = new FileSystemPathIdFixture();
_pathSegmentFixture = new PathSegmentFixture();
}
#endregion
#region ===================================================================== METHODS ===================================================================================
[Fact]
public void IsValidPath_WithValidPath_ShouldReturnTrue()
{
// Arrange
string validPath = @"C:\ValidPath";
FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(validPath);
_mockPathStrategy.IsValidPath(pathId).Returns(true);
// Act
bool result = _sut.IsValidPath(validPath);
// Assert
result.Should().BeTrue();
_mockPathStrategy.Received(1).IsValidPath(Arg.Is<FileSystemPathId>(id => id.Path == validPath));
}
[Fact]
public void IsValidPath_WithInvalidPath_ShouldReturnFalse()
{
// Arrange
string invalidPath = @"C:\Invalid\*Path";
FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(invalidPath);
_mockPathStrategy.IsValidPath(pathId).Returns(false);
// Act
bool result = _sut.IsValidPath(invalidPath);
// Assert
result.Should().BeFalse();
_mockPathStrategy.Received(1).IsValidPath(Arg.Is<FileSystemPathId>(id => id.Path == invalidPath));
}
[Fact]
public void IsValidPath_WithEmptyPath_ShouldReturnFalse()
{
// Arrange
string emptyPath = string.Empty;
// Act
bool result = _sut.IsValidPath(emptyPath);
// Assert
result.Should().BeFalse();
_mockPathStrategy.DidNotReceive().IsValidPath(Arg.Any<FileSystemPathId>());
}
[Fact]
public void IsValidPath_WithNullPath_ShouldReturnFalse()
{
// Arrange
string? nullPath = null;
// Act
bool result = _sut.IsValidPath(nullPath!);
// Assert
result.Should().BeFalse();
_mockPathStrategy.DidNotReceive().IsValidPath(Arg.Any<FileSystemPathId>());
}
[Fact]
public void Exists_WithValidExistingPath_ShouldReturnTrue()
{
// Arrange
string existingPath = @"C:\ExistingPath";
FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(existingPath);
_mockPathStrategy.Exists(pathId).Returns(true);
// Act
bool result = _sut.Exists(existingPath);
// Assert
result.Should().BeTrue();
_mockPathStrategy.Received(1).Exists(Arg.Is<FileSystemPathId>(id => id.Path == existingPath));
}
[Fact]
public void Exists_WithValidNonExistingPath_ShouldReturnFalse()
{
// Arrange
string nonExistingPath = @"C:\NonExistingPath";
FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(nonExistingPath);
_mockPathStrategy.Exists(pathId).Returns(false);
// Act
bool result = _sut.Exists(nonExistingPath);
// Assert
result.Should().BeFalse();
_mockPathStrategy.Received(1).Exists(Arg.Is<FileSystemPathId>(id => id.Path == nonExistingPath));
}
[Fact]
public void Exists_WithEmptyPath_ShouldReturnFalse()
{
// Arrange
string emptyPath = string.Empty;
// Act
bool result = _sut.Exists(emptyPath);
// Assert
result.Should().BeFalse();
_mockPathStrategy.DidNotReceive().Exists(Arg.Any<FileSystemPathId>());
}
[Fact]
public void Exists_WithNullPath_ShouldReturnFalse()
{
// Arrange
string? nullPath = null;
// Act
bool result = _sut.Exists(nullPath!);
// Assert
result.Should().BeFalse();
_mockPathStrategy.DidNotReceive().Exists(Arg.Any<FileSystemPathId>());
}
[Fact]
public void CombinePath_WithValidPathAndName_ShouldReturnCombinedPath()
{
// Arrange
string path = @"C:\BaseDir";
string name = "SubDir";
FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path);
FileSystemPathId combinedPathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\BaseDir\SubDir");
_mockPathStrategy.CombinePath(pathId, name).Returns(ErrorOrFactory.From(combinedPathId));
// Act
ErrorOr<string> result = _sut.CombinePath(path, name);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().Be(@"C:\BaseDir\SubDir");
_mockPathStrategy.Received(1).CombinePath(Arg.Is<FileSystemPathId>(id => id.Path == path), name);
}
[Fact]
public void CombinePath_WithInvalidPath_ShouldReturnError()
{
// Arrange
string invalidPath = string.Empty;
string name = "SubDir";
// Act
ErrorOr<string> result = _sut.CombinePath(invalidPath, name);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.FileManagement.InvalidPath);
_mockPathStrategy.DidNotReceive().CombinePath(Arg.Any<FileSystemPathId>(), Arg.Any<string>());
}
[Fact]
public void CombinePath_WhenPathStrategyReturnsError_ShouldPropagateError()
{
// Arrange
string path = @"C:\BaseDir";
string name = "Invalid*Name";
FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path);
_mockPathStrategy.CombinePath(pathId, name).Returns(Errors.FileManagement.InvalidPath);
// Act
ErrorOr<string> result = _sut.CombinePath(path, name);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.FileManagement.InvalidPath);
_mockPathStrategy.Received(1).CombinePath(Arg.Is<FileSystemPathId>(id => id.Path == path), name);
}
[Fact]
public void CombinePath_WithNullName_ShouldReturnError()
{
// Arrange
string path = @"C:\BaseDir";
string? name = null;
// Act
ErrorOr<string> result = _sut.CombinePath(path, name!);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.FileManagement.InvalidPath);
_mockPathStrategy.DidNotReceive().CombinePath(Arg.Any<FileSystemPathId>(), Arg.Any<string>());
}
[Fact]
public void ParsePath_WithValidPath_ShouldReturnPathSegments()
{
// Arrange
string validPath = @"C:\ValidPath\SubDir";
FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(validPath);
List<PathSegment> expectedSegments = _pathSegmentFixture.CreateMany();
_mockPathStrategy.ParsePath(pathId).Returns(ErrorOrFactory.From(expectedSegments.AsEnumerable()));
// Act
ErrorOr<IEnumerable<PathSegment>> result = _sut.ParsePath(validPath);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeEquivalentTo(expectedSegments);
_mockPathStrategy.Received(1).ParsePath(Arg.Is<FileSystemPathId>(id => id.Path == validPath));
}
[Fact]
public void ParsePath_WithInvalidPath_ShouldReturnError()
{
// Arrange
string invalidPath = string.Empty;
// Act
ErrorOr<IEnumerable<PathSegment>> result = _sut.ParsePath(invalidPath);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.FileManagement.InvalidPath);
_mockPathStrategy.DidNotReceive().ParsePath(Arg.Any<FileSystemPathId>());
}
[Fact]
public void ParsePath_WhenPathStrategyReturnsError_ShouldPropagateError()
{
// Arrange
string path = @"C:\InvalidPath\*SubDir";
FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path);
_mockPathStrategy.ParsePath(pathId).Returns(Errors.FileManagement.InvalidPath);
// Act
ErrorOr<IEnumerable<PathSegment>> result = _sut.ParsePath(path);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.FileManagement.InvalidPath);
_mockPathStrategy.Received(1).ParsePath(Arg.Is<FileSystemPathId>(id => id.Path == path));
}
[Fact]
public void ParsePath_WithNullPath_ShouldReturnError()
{
// Arrange
string? nullPath = null;
// Act
ErrorOr<IEnumerable<PathSegment>> result = _sut.ParsePath(nullPath!);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.FileManagement.InvalidPath);
_mockPathStrategy.DidNotReceive().ParsePath(Arg.Any<FileSystemPathId>());
}
[Fact]
public void GoUpOneLevel_WithValidPath_ShouldReturnParentPathSegments()
{
// Arrange
string validPath = @"C:\ValidPath\SubDir";
FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(validPath);
List<PathSegment> expectedSegments = _pathSegmentFixture.CreateMany(2); // Assuming parent path has 2 segments
_mockPathStrategy.GoUpOneLevel(pathId).Returns(ErrorOrFactory.From(expectedSegments.AsEnumerable()));
// Act
ErrorOr<IEnumerable<PathSegment>> result = _sut.GoUpOneLevel(validPath);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeEquivalentTo(expectedSegments);
_mockPathStrategy.Received(1).GoUpOneLevel(Arg.Is<FileSystemPathId>(id => id.Path == validPath));
}
[Fact]
public void GoUpOneLevel_WithRootPath_ShouldReturnEmptySegmentList()
{
// Arrange
string rootPath = @"C:\";
FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(rootPath);
List<PathSegment> emptySegmentList = [];
_mockPathStrategy.GoUpOneLevel(pathId).Returns(ErrorOrFactory.From(emptySegmentList.AsEnumerable()));
// Act
ErrorOr<IEnumerable<PathSegment>> result = _sut.GoUpOneLevel(rootPath);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeEmpty();
_mockPathStrategy.Received(1).GoUpOneLevel(Arg.Is<FileSystemPathId>(id => id.Path == rootPath));
}
[Fact]
public void GoUpOneLevel_WithInvalidPath_ShouldReturnError()
{
// Arrange
string invalidPath = string.Empty;
// Act
ErrorOr<IEnumerable<PathSegment>> result = _sut.GoUpOneLevel(invalidPath);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.FileManagement.InvalidPath);
_mockPathStrategy.DidNotReceive().GoUpOneLevel(Arg.Any<FileSystemPathId>());
}
[Fact]
public void GoUpOneLevel_WhenPathStrategyReturnsError_ShouldPropagateError()
{
// Arrange
string path = @"C:\InvalidPath\*SubDir";
FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path);
_mockPathStrategy.GoUpOneLevel(pathId).Returns(Errors.FileManagement.InvalidPath);
// Act
ErrorOr<IEnumerable<PathSegment>> result = _sut.GoUpOneLevel(path);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.FileManagement.InvalidPath);
_mockPathStrategy.Received(1).GoUpOneLevel(Arg.Is<FileSystemPathId>(id => id.Path == path));
}
[Fact]
public void GoUpOneLevel_WithNullPath_ShouldReturnError()
{
// Arrange
string? nullPath = null;
// Act
ErrorOr<IEnumerable<PathSegment>> result = _sut.GoUpOneLevel(nullPath!);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.FileManagement.InvalidPath);
_mockPathStrategy.DidNotReceive().GoUpOneLevel(Arg.Any<FileSystemPathId>());
}
[Fact]
public void GetInvalidPathCharsForPlatform_WhenCalled_ShouldReturnInvalidCharsFromPathStrategy()
{
// Arrange
char[] expectedInvalidChars = ['<', '>', ':', '"', '|', '?', '*'];
_mockPathStrategy.GetInvalidPathCharsForPlatform().Returns(expectedInvalidChars);
// Act
char[] result = _sut.GetInvalidPathCharsForPlatform();
// Assert
result.Should().BeEquivalentTo(expectedInvalidChars);
_mockPathStrategy.Received(1).GetInvalidPathCharsForPlatform();
}
[Fact]
public void GetInvalidPathCharsForPlatform_WhenPathStrategyReturnsEmptyArray_ShouldReturnEmptyArray()
{
// Arrange
char[] emptyArray = [];
_mockPathStrategy.GetInvalidPathCharsForPlatform().Returns(emptyArray);
// Act
char[] result = _sut.GetInvalidPathCharsForPlatform();
// Assert
result.Should().BeEmpty();
_mockPathStrategy.Received(1).GetInvalidPathCharsForPlatform();
}
[Fact]
public void GetInvalidPathCharsForPlatform_WhenReturnedArrayIsModified_ShouldNotAffectSubsequentCalls()
{
// Arrange
char[] originalInvalidChars = ['<', '>', ':', '"', '|', '?', '*'];
_mockPathStrategy.GetInvalidPathCharsForPlatform().Returns(originalInvalidChars);
// Act
char[] result = _sut.GetInvalidPathCharsForPlatform();
result[0] = 'X'; // Attempt to modify the returned array
// Assert
char[] secondResult = _sut.GetInvalidPathCharsForPlatform();
secondResult.Should().BeEquivalentTo(originalInvalidChars);
_mockPathStrategy.Received(2).GetInvalidPathCharsForPlatform();
}
[Fact]
public void GetPathRoot_WhenCalledWithValidPath_ShouldReturnRootPathSegment()
{
// Arrange
string validPath = @"C:\ValidPath\SubDir";
FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(validPath);
PathSegment expectedRootSegment = _pathSegmentFixture.CreatePathSegment(name: "C:", isDirectory: false, isDrive: true);
_mockPathStrategy.GetPathRoot(pathId).Returns(ErrorOrFactory.From(expectedRootSegment));
// Act
ErrorOr<PathSegment> result = _sut.GetPathRoot(validPath);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeEquivalentTo(expectedRootSegment);
_mockPathStrategy.Received(1).GetPathRoot(Arg.Is<FileSystemPathId>(id => id.Path == validPath));
}
[Fact]
public void GetPathRoot_WhenCalledWithInvalidPath_ShouldReturnError()
{
// Arrange
string invalidPath = string.Empty;
// Act
ErrorOr<PathSegment> result = _sut.GetPathRoot(invalidPath);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.FileManagement.InvalidPath);
_mockPathStrategy.DidNotReceive().GetPathRoot(Arg.Any<FileSystemPathId>());
}
[Fact]
public void GetPathRoot_WhenPathStrategyReturnsError_ShouldPropagateError()
{
// Arrange
string path = @"C:\InvalidPath\*SubDir";
FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path);
_mockPathStrategy.GetPathRoot(pathId).Returns(Errors.FileManagement.InvalidPath);
// Act
ErrorOr<PathSegment> result = _sut.GetPathRoot(path);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.FileManagement.InvalidPath);
_mockPathStrategy.Received(1).GetPathRoot(Arg.Is<FileSystemPathId>(id => id.Path == path));
}
[Fact]
public void GetPathRoot_WhenCalledWithNullPath_ShouldReturnError()
{
// Arrange
string? nullPath = null;
// Act
ErrorOr<PathSegment> result = _sut.GetPathRoot(nullPath!);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.FileManagement.InvalidPath);
_mockPathStrategy.DidNotReceive().GetPathRoot(Arg.Any<FileSystemPathId>());
}
#endregion
}
@@ -0,0 +1,195 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FluentAssertions;
using Lumina.Contracts.Enums.PhotoLibrary;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Environment;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects;
using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Services.Fixtures;
using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects.Fixtures;
using NSubstitute;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats.Jpeg;
using SixLabors.ImageSharp.PixelFormats;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Services;
/// <summary>
/// Contains unit tests for the <see cref="ThumbnailService"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ThumbnailServiceTests
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly IEnvironmentContext _mockEnvironmentContext;
private readonly ThumbnailService _sut;
private readonly FileSystemPathIdFixture _fileSystemPathIdFixture;
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="ThumbnailServiceTests"/> class.
/// </summary>
public ThumbnailServiceTests()
{
_mockEnvironmentContext = Substitute.For<IEnvironmentContext>();
_sut = new ThumbnailService(_mockEnvironmentContext);
_fileSystemPathIdFixture = new FileSystemPathIdFixture();
}
#endregion
#region ===================================================================== METHODS ===================================================================================
[Fact]
public async Task GetThumbnailAsync_WithValidPath_ShouldReturnThumbnail()
{
// Arrange
string path = @"C:\TestImage.jpg";
int quality = 80;
FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path);
// Create a small valid JPEG image
byte[] imageBytes;
using (Image<Rgba32> image = new(10, 10))
{
using MemoryStream ms = new();
image.Save(ms, new JpegEncoder());
imageBytes = ms.ToArray();
}
_mockEnvironmentContext.FileTypeService.GetImageTypeAsync(pathId, Arg.Any<CancellationToken>())
.Returns(ErrorOrFactory.From(ImageType.JPEG));
_mockEnvironmentContext.FileProviderService.GetFileAsync(pathId)
.Returns(ErrorOrFactory.From(imageBytes));
// Act
ErrorOr<Thumbnail> result = await _sut.GetThumbnailAsync(path, quality, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Type.Should().Be(ImageType.JPEG);
result.Value.Bytes.Should().NotBeEmpty();
}
[Fact]
public async Task GetThumbnailAsync_WithInvalidPath_ShouldReturnError()
{
// Arrange
string invalidPath = string.Empty;
int quality = 80;
// Act
ErrorOr<Thumbnail> result = await _sut.GetThumbnailAsync(invalidPath, quality, CancellationToken.None);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.FileManagement.InvalidPath);
}
[Fact]
public async Task GetThumbnailAsync_WhenFileTypeServiceReturnsError_ShouldPropagateError()
{
// Arrange
FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestImage.jpg");
int quality = 80;
_mockEnvironmentContext.FileTypeService.GetImageTypeAsync(pathId, Arg.Any<CancellationToken>())
.Returns(Errors.Permission.UnauthorizedAccess);
// Act
ErrorOr<Thumbnail> result = await _sut.GetThumbnailAsync(pathId, quality, CancellationToken.None);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess);
}
[Fact]
public async Task GetThumbnailAsync_WhenImageTypeIsNone_ShouldReturnNoThumbnailError()
{
// Arrange
FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestFile.txt");
int quality = 80;
_mockEnvironmentContext.FileTypeService.GetImageTypeAsync(pathId, Arg.Any<CancellationToken>())
.Returns(ErrorOrFactory.From(ImageType.None));
// Act
ErrorOr<Thumbnail> result = await _sut.GetThumbnailAsync(pathId, quality, CancellationToken.None);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.Thumbnails.NoThumbnail);
}
[Fact]
public async Task GetThumbnailAsync_WhenFileProviderServiceReturnsError_ShouldPropagateError()
{
// Arrange
FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestImage.jpg");
int quality = 80;
_mockEnvironmentContext.FileTypeService.GetImageTypeAsync(pathId, Arg.Any<CancellationToken>())
.Returns(ErrorOrFactory.From(ImageType.JPEG));
_mockEnvironmentContext.FileProviderService.GetFileAsync(pathId)
.Returns(Errors.Permission.UnauthorizedAccess);
// Act
ErrorOr<Thumbnail> result = await _sut.GetThumbnailAsync(pathId, quality, CancellationToken.None);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.Permission.UnauthorizedAccess);
}
[Theory]
[ClassData(typeof(ImageTypeFixture))]
public async Task GetThumbnailAsync_WithDifferentImageTypes_ShouldReturnThumbnail(ImageType imageType, byte[] imageBytes)
{
// Arrange
FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestImage");
int quality = 80;
_mockEnvironmentContext.FileTypeService.GetImageTypeAsync(pathId, Arg.Any<CancellationToken>())
.Returns(ErrorOrFactory.From(imageType));
_mockEnvironmentContext.FileProviderService.GetFileAsync(pathId)
.Returns(ErrorOrFactory.From(imageBytes));
// Act
ErrorOr<Thumbnail> result = await _sut.GetThumbnailAsync(pathId, quality, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Type.Should().Be(imageType);
result.Value.Bytes.Should().NotBeEmpty();
using (MemoryStream ms = new(result.Value.Bytes))
{
Image loadedImage = Image.Load(ms);
loadedImage.Should().NotBeNull();
}
}
[Fact]
public async Task GetThumbnailAsync_WithCancellation_ShouldThrowTaskCanceledException()
{
// Arrange
FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestImage.jpg");
int quality = 80;
CancellationTokenSource cts = new();
cts.Cancel();
_mockEnvironmentContext.FileTypeService.GetImageTypeAsync(pathId, cts.Token)
.Returns(Task.FromCanceled<ErrorOr<ImageType>>(cts.Token));
// Act & Assert
await Assert.ThrowsAsync<TaskCanceledException>(() =>
_sut.GetThumbnailAsync(pathId, quality, cts.Token));
}
#endregion
}
@@ -0,0 +1,99 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Environment;
using NSubstitute;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Strategies.Environment;
/// <summary>
/// Contains unit tests for the <see cref="EnvironmentContext"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class EnvironmentContextTests
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly IDirectoryProviderService _mockDirectoryProviderService;
private readonly IFileProviderService _mockFileProviderService;
private readonly IFileTypeService _mockFileTypeService;
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="EnvironmentContextTests"/> class.
/// </summary>
public EnvironmentContextTests()
{
_mockDirectoryProviderService = Substitute.For<IDirectoryProviderService>();
_mockFileProviderService = Substitute.For<IFileProviderService>();
_mockFileTypeService = Substitute.For<IFileTypeService>();
}
#endregion
#region ===================================================================== METHODS ===================================================================================
[Fact]
public void Constructor_WhenCalledWithValidParameters_ShouldInitializeAllProperties()
{
// Arrange & Act
EnvironmentContext environmentContext = new(
_mockDirectoryProviderService,
_mockFileProviderService,
_mockFileTypeService);
// Assert
environmentContext.DirectoryProviderService.Should().Be(_mockDirectoryProviderService);
environmentContext.FileProviderService.Should().Be(_mockFileProviderService);
environmentContext.FileTypeService.Should().Be(_mockFileTypeService);
}
[Fact]
public void FileTypeService_WhenAccessed_ShouldReturnInjectedService()
{
// Arrange
EnvironmentContext environmentContext = new(
_mockDirectoryProviderService,
_mockFileProviderService,
_mockFileTypeService);
// Act
IFileTypeService result = environmentContext.FileTypeService;
// Assert
result.Should().Be(_mockFileTypeService);
}
[Fact]
public void FileProviderService_WhenAccessed_ShouldReturnInjectedService()
{
// Arrange
EnvironmentContext environmentContext = new(
_mockDirectoryProviderService,
_mockFileProviderService,
_mockFileTypeService);
// Act
IFileProviderService result = environmentContext.FileProviderService;
// Assert
result.Should().Be(_mockFileProviderService);
}
[Fact]
public void DirectoryProviderService_WhenAccessed_ShouldReturnInjectedService()
{
// Arrange
EnvironmentContext environmentContext = new(
_mockDirectoryProviderService,
_mockFileProviderService,
_mockFileTypeService);
// Act
IDirectoryProviderService result = environmentContext.DirectoryProviderService;
// Assert
result.Should().Be(_mockDirectoryProviderService);
}
#endregion
}
@@ -0,0 +1,536 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FluentAssertions;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Path;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects;
using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects.Fixtures;
using NSubstitute;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO.Abstractions;
using System.Linq;
#endregion
namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Strategies.Path;
/// <summary>
/// Contains unit tests for the <see cref="UnixPathStrategy"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UnixPathStrategyTests
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly IFileSystem _mockFileSystem;
private readonly UnixPathStrategy _sut;
private readonly FileSystemPathIdFixture _fileSystemPathIdFixture;
private readonly PathSegmentFixture _pathSegmentFixture;
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="UnixPathStrategyTests"/> class.
/// </summary>
public UnixPathStrategyTests()
{
_mockFileSystem = Substitute.For<IFileSystem>();
_sut = new UnixPathStrategy(_mockFileSystem);
_fileSystemPathIdFixture = new FileSystemPathIdFixture();
_pathSegmentFixture = new PathSegmentFixture();
}
#endregion
#region ===================================================================== METHODS ===================================================================================
[Theory]
[InlineData("/home/user")]
[InlineData("/var/log/")]
[InlineData("/etc/config.conf")]
[InlineData("/")]
[InlineData("/usr/local/bin")]
public void IsValidPath_WithValidUnixPaths_ShouldReturnTrue(string path)
{
// Arrange
FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path);
// Act
bool result = _sut.IsValidPath(pathId);
// Assert
result.Should().BeTrue();
}
[Theory]
[InlineData("C:\\Windows\\System32")]
[InlineData("relative/path")]
[InlineData("./relative/path")]
[InlineData("../parent/path")]
public void IsValidPath_WithInvalidUnixPaths_ShouldReturnFalse(string path)
{
// Arrange
FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path);
// Act
bool result = _sut.IsValidPath(pathId);
// Assert
result.Should().BeFalse();
}
[Fact]
public void IsValidPath_WithPathContainingInvalidCharacters_ShouldReturnFalse()
{
// Arrange
string invalidPath = "/home/user/file\0name";
FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(invalidPath);
// Act
bool result = _sut.IsValidPath(pathId);
// Assert
result.Should().BeFalse();
}
[Theory]
[InlineData("/home/user/file with spaces")]
[InlineData("/home/user/file-with-dashes")]
[InlineData("/home/user/file_with_underscores")]
[InlineData("/home/user/file.with.dots")]
[InlineData("/home/user/file~with~tilde")]
[InlineData("/home/user/file!with!exclamation")]
[InlineData("/home/user/file$with$dollar")]
[InlineData("/home/user/file&with&ampersand")]
[InlineData("/home/user/file'with'singlequote")]
[InlineData("/home/user/file(with)parentheses")]
public void IsValidPath_WithValidSpecialCharacters_ShouldReturnTrue(string path)
{
// Arrange
FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path);
// Act
bool result = _sut.IsValidPath(pathId);
// Assert
result.Should().BeTrue();
}
[Fact]
public void IsValidPath_WithVeryLongPath_ShouldReturnTrue()
{
// Arrange
string longPath = "/" + string.Join("/", Enumerable.Repeat("a", 100));
FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(longPath);
// Act
bool result = _sut.IsValidPath(pathId);
// Assert
result.Should().BeTrue();
}
[Fact]
public void Exists_WhenPathExists_ShouldReturnTrue()
{
// Arrange
string existingPath = "/home/user/existing_file.txt";
FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(existingPath);
_mockFileSystem.Path.Exists(existingPath).Returns(true);
// Act
bool result = _sut.Exists(pathId);
// Assert
result.Should().BeTrue();
_mockFileSystem.Path.Received(1).Exists(existingPath);
}
[Fact]
public void Exists_WhenPathDoesNotExist_ShouldReturnFalse()
{
// Arrange
string nonExistingPath = "/home/user/non_existing_file.txt";
FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(nonExistingPath);
_mockFileSystem.Path.Exists(nonExistingPath).Returns(false);
// Act
bool result = _sut.Exists(pathId);
// Assert
result.Should().BeFalse();
_mockFileSystem.Path.Received(1).Exists(nonExistingPath);
}
[Fact]
public void Exists_WithRootPath_ShouldCheckExistence()
{
// Arrange
string rootPath = "/";
FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(rootPath);
_mockFileSystem.Path.Exists(rootPath).Returns(true);
// Act
bool result = _sut.Exists(pathId);
// Assert
result.Should().BeTrue();
_mockFileSystem.Path.Received(1).Exists(rootPath);
}
[Fact]
public void Exists_WithDirectoryPath_ShouldCheckExistence()
{
// Arrange
string directoryPath = "/home/user/documents/";
FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(directoryPath);
_mockFileSystem.Path.Exists(directoryPath).Returns(true);
// Act
bool result = _sut.Exists(pathId);
// Assert
result.Should().BeTrue();
_mockFileSystem.Path.Received(1).Exists(directoryPath);
}
[Fact]
public void Exists_WithFilePath_ShouldCheckExistence()
{
// Arrange
string filePath = "/home/user/documents/file.txt";
FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(filePath);
_mockFileSystem.Path.Exists(filePath).Returns(true);
// Act
bool result = _sut.Exists(pathId);
// Assert
result.Should().BeTrue();
_mockFileSystem.Path.Received(1).Exists(filePath);
}
[Fact]
public void CombinePath_WithValidPathAndName_ShouldReturnCombinedPath()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/home/user");
string name = "documents";
// Act
ErrorOr<FileSystemPathId> result = _sut.CombinePath(path, name);
// Assert
result.IsError.Should().BeFalse();
result.Value.Path.Should().Be("/home/user/documents/");
}
[Fact]
public void CombinePath_WithTrailingSlashInPath_ShouldReturnCorrectlyCombinedPath()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/home/user/");
string name = "documents";
// Act
ErrorOr<FileSystemPathId> result = _sut.CombinePath(path, name);
// Assert
result.IsError.Should().BeFalse();
result.Value.Path.Should().Be("/home/user/documents/");
}
[Fact]
public void CombinePath_WithLeadingSlashInName_ShouldReturnCorrectlyCombinedPath()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/home/user");
string name = "/documents";
// Act
ErrorOr<FileSystemPathId> result = _sut.CombinePath(path, name);
// Assert
result.IsError.Should().BeFalse();
result.Value.Path.Should().Be("/home/user/documents/");
}
[Fact]
public void CombinePath_WithEmptyName_ShouldReturnError()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/home/user");
string name = "";
// Act
ErrorOr<FileSystemPathId> result = _sut.CombinePath(path, name);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.FileManagement.NameCannotBeEmpty);
}
[Fact]
public void CombinePath_WithNullName_ShouldReturnError()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/home/user");
string name = null!;
// Act
ErrorOr<FileSystemPathId> result = _sut.CombinePath(path, name);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.FileManagement.NameCannotBeEmpty);
}
[Fact]
public void CombinePath_WithRootPath_ShouldReturnCorrectlyCombinedPath()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/");
string name = "home";
// Act
ErrorOr<FileSystemPathId> result = _sut.CombinePath(path, name);
// Assert
result.IsError.Should().BeFalse();
result.Value.Path.Should().Be("/home/");
}
[Fact]
public void ParsePath_WithValidUnixPath_ShouldReturnCorrectPathSegments()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/home/user/documents/file.txt");
// Act
ErrorOr<IEnumerable<PathSegment>> result = _sut.ParsePath(path);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().HaveCount(5);
result.Value.ElementAt(0).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("/", false, true));
result.Value.ElementAt(1).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("home", true, false));
result.Value.ElementAt(2).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("user", true, false));
result.Value.ElementAt(3).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("documents", true, false));
result.Value.ElementAt(4).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("file.txt", false, false));
}
[Fact]
public void ParsePath_WithRootPath_ShouldReturnSingleRootSegment()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/");
// Act
ErrorOr<IEnumerable<PathSegment>> result = _sut.ParsePath(path);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().HaveCount(1);
result.Value.Single().Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("/", false, true));
}
[Fact]
public void ParsePath_WithTrailingSlash_ShouldTreatLastSegmentAsDirectory()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/home/user/documents/");
// Act
ErrorOr<IEnumerable<PathSegment>> result = _sut.ParsePath(path);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().HaveCount(4);
result.Value.Last().Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("documents", true, false));
}
[Fact]
public void ParsePath_WithRelativePath_ShouldReturnError()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("home/user");
// Act
ErrorOr<IEnumerable<PathSegment>> result = _sut.ParsePath(path);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.FileManagement.InvalidPath);
}
[Fact]
public void ParsePath_WithPathContainingDots_ShouldParseCorrectly()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/home/user/file.with.dots.txt");
// Act
ErrorOr<IEnumerable<PathSegment>> result = _sut.ParsePath(path);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().HaveCount(4);
result.Value.Last().Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("file.with.dots.txt", false, false));
}
[Fact]
public void GoUpOneLevel_WithValidPath_ShouldReturnParentPath()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/home/user/documents");
// Act
ErrorOr<IEnumerable<PathSegment>> result = _sut.GoUpOneLevel(path);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().HaveCount(3);
result.Value.ElementAt(0).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("/", false, true));
result.Value.ElementAt(1).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("home", true, false));
result.Value.ElementAt(2).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("user", true, false));
}
[Fact]
public void GoUpOneLevel_WithRootPath_ShouldReturnError()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/");
// Act
ErrorOr<IEnumerable<PathSegment>> result = _sut.GoUpOneLevel(path);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.FileManagement.CannotNavigateUp);
}
[Fact]
public void GoUpOneLevel_WithTrailingSlash_ShouldReturnCorrectParentPath()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/home/user/");
// Act
ErrorOr<IEnumerable<PathSegment>> result = _sut.GoUpOneLevel(path);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().HaveCount(2);
result.Value.ElementAt(0).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("/", false, true));
result.Value.ElementAt(1).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("home", true, false));
}
[Fact]
public void GoUpOneLevel_WithInvalidPath_ShouldReturnError()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("invalid/path");
// Act
ErrorOr<IEnumerable<PathSegment>> result = _sut.GoUpOneLevel(path);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.FileManagement.InvalidPath);
}
[Fact]
public void GoUpOneLevel_WithSingleLevelPath_ShouldReturnRootPath()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/home");
// Act
ErrorOr<IEnumerable<PathSegment>> result = _sut.GoUpOneLevel(path);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().HaveCount(1);
result.Value.Single().Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("/", false, true));
}
[Fact]
public void GetInvalidPathCharsForPlatform_WhenCalled_ShouldReturnOnlyNullCharacter()
{
// Act
char[] result = _sut.GetInvalidPathCharsForPlatform();
// Assert
result.Should().HaveCount(1);
result.Should().Contain('\0');
}
[Fact]
public void GetInvalidPathCharsForPlatform_WhenCalled_ShouldNotContainOtherCharacters()
{
// Act
char[] result = _sut.GetInvalidPathCharsForPlatform();
// Assert
result.Should().NotContain('/');
result.Should().NotContain('\\');
result.Should().NotContain(':');
result.Should().NotContain('*');
result.Should().NotContain('?');
result.Should().NotContain('"');
result.Should().NotContain('<');
result.Should().NotContain('>');
result.Should().NotContain('|');
}
[Fact]
public void GetInvalidPathCharsForPlatform_WhenCalled_ShouldReturnSameResultOnMultipleCalls()
{
// Act
char[] result1 = _sut.GetInvalidPathCharsForPlatform();
char[] result2 = _sut.GetInvalidPathCharsForPlatform();
// Assert
result1.Should().BeEquivalentTo(result2);
}
[Fact]
public void GetPathRoot_WithValidUnixPath_ShouldReturnRootSegment()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/home/user/documents");
// Act
ErrorOr<PathSegment> result = _sut.GetPathRoot(path);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("/", false, true));
}
[Fact]
public void GetPathRoot_WithRootPath_ShouldReturnRootSegment()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("/");
// Act
ErrorOr<PathSegment> result = _sut.GetPathRoot(path);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("/", false, true));
}
[Fact]
public void GetPathRoot_WithInvalidPath_ShouldReturnError()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId("home/user");
// Act
ErrorOr<PathSegment> result = _sut.GetPathRoot(path);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.FileManagement.InvalidPath);
}
#endregion
}
@@ -0,0 +1,753 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FluentAssertions;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Path;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects;
using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects.Fixtures;
using NSubstitute;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO.Abstractions;
using System.Linq;
#endregion
namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Strategies.Path;
/// <summary>
/// Contains unit tests for the <see cref="WindowsPathStrategy"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class WindowsPathStrategyTests
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly IFileSystem _mockFileSystem;
private readonly WindowsPathStrategy _sut;
private readonly FileSystemPathIdFixture _fileSystemPathIdFixture;
private readonly PathSegmentFixture _pathSegmentFixture;
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="WindowsPathStrategyTests"/> class.
/// </summary>
public WindowsPathStrategyTests()
{
_mockFileSystem = Substitute.For<IFileSystem>();
_sut = new WindowsPathStrategy(_mockFileSystem);
_fileSystemPathIdFixture = new FileSystemPathIdFixture();
_pathSegmentFixture = new PathSegmentFixture();
}
#endregion
#region ===================================================================== METHODS ===================================================================================
[Theory]
[InlineData(@"C:\Users\User")]
[InlineData(@"D:\Program Files\")]
[InlineData(@"E:\Documents\file.txt")]
[InlineData(@"F:\")]
[InlineData(@"G:\Projects\Visual Studio 2022\")]
public void IsValidPath_WithValidWindowsPaths_ShouldReturnTrue(string path)
{
// Arrange
FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path);
// Act
bool result = _sut.IsValidPath(pathId);
// Assert
result.Should().BeTrue();
}
[Theory]
[InlineData("/home/user")]
[InlineData("relative\\path")]
[InlineData(".\\relative\\path")]
[InlineData("..\\parent\\path")]
[InlineData("C:invalid_path")]
public void IsValidPath_WithInvalidWindowsPaths_ShouldReturnFalse(string path)
{
// Arrange
FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path);
// Act
bool result = _sut.IsValidPath(pathId);
// Assert
result.Should().BeFalse();
}
[Fact]
public void IsValidPath_WithPathContainingInvalidCharacters_ShouldReturnFalse()
{
// Arrange
string invalidPath = @"C:\Users\User\file<name>";
FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(invalidPath);
// Act
bool result = _sut.IsValidPath(pathId);
// Assert
result.Should().BeFalse();
}
[Theory]
[InlineData(@"C:\Users\User\file with spaces")]
[InlineData(@"D:\Projects\file-with-dashes")]
[InlineData(@"E:\Documents\file_with_underscores")]
[InlineData(@"F:\Data\file.with.dots")]
[InlineData(@"G:\Backups\file(with)parentheses")]
public void IsValidPath_WithValidSpecialCharacters_ShouldReturnTrue(string path)
{
// Arrange
FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path);
// Act
bool result = _sut.IsValidPath(pathId);
// Assert
result.Should().BeTrue();
}
[Fact]
public void IsValidPath_WithVeryLongPath_ShouldReturnTrue()
{
// Arrange
string longPath = @"C:\" + string.Join("\\", Enumerable.Repeat("a", 100));
FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(longPath);
// Act
bool result = _sut.IsValidPath(pathId);
// Assert
result.Should().BeTrue();
}
[Theory]
[InlineData(@"\\server\share")]
[InlineData(@"\\server\share\folder")]
[InlineData(@"\\server\share\folder\file.txt")]
public void IsValidPath_WithValidUNCPaths_ShouldReturnTrue(string path)
{
// Arrange
FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path);
// Act
bool result = _sut.IsValidPath(pathId);
// Assert
result.Should().BeTrue();
}
[Theory]
[InlineData(@"\\")]
[InlineData(@"\\server")]
[InlineData(@"\\\server\share")]
public void IsValidPath_WithInvalidUNCPaths_ShouldReturnFalse(string path)
{
// Arrange
FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(path);
// Act
bool result = _sut.IsValidPath(pathId);
// Assert
result.Should().BeFalse();
}
[Fact]
public void Exists_WhenPathExists_ShouldReturnTrue()
{
// Arrange
string existingPath = @"C:\Users\User\existing_file.txt";
FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(existingPath);
_mockFileSystem.Path.Exists(existingPath).Returns(true);
// Act
bool result = _sut.Exists(pathId);
// Assert
result.Should().BeTrue();
_mockFileSystem.Path.Received(1).Exists(existingPath);
}
[Fact]
public void Exists_WhenPathDoesNotExist_ShouldReturnFalse()
{
// Arrange
string nonExistingPath = @"C:\Users\User\non_existing_file.txt";
FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(nonExistingPath);
_mockFileSystem.Path.Exists(nonExistingPath).Returns(false);
// Act
bool result = _sut.Exists(pathId);
// Assert
result.Should().BeFalse();
_mockFileSystem.Path.Received(1).Exists(nonExistingPath);
}
[Fact]
public void Exists_WithRootPath_ShouldCheckExistence()
{
// Arrange
string rootPath = @"C:\";
FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(rootPath);
_mockFileSystem.Path.Exists(rootPath).Returns(true);
// Act
bool result = _sut.Exists(pathId);
// Assert
result.Should().BeTrue();
_mockFileSystem.Path.Received(1).Exists(rootPath);
}
[Fact]
public void Exists_WithDirectoryPath_ShouldCheckExistence()
{
// Arrange
string directoryPath = @"C:\Users\User\Documents\";
FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(directoryPath);
_mockFileSystem.Path.Exists(directoryPath).Returns(true);
// Act
bool result = _sut.Exists(pathId);
// Assert
result.Should().BeTrue();
_mockFileSystem.Path.Received(1).Exists(directoryPath);
}
[Fact]
public void Exists_WithFilePath_ShouldCheckExistence()
{
// Arrange
string filePath = @"C:\Users\User\Documents\file.txt";
FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(filePath);
_mockFileSystem.Path.Exists(filePath).Returns(true);
// Act
bool result = _sut.Exists(pathId);
// Assert
result.Should().BeTrue();
_mockFileSystem.Path.Received(1).Exists(filePath);
}
[Fact]
public void Exists_WithUNCPath_ShouldCheckExistence()
{
// Arrange
string uncPath = @"\\server\share\folder\file.txt";
FileSystemPathId pathId = _fileSystemPathIdFixture.CreateFileSystemPathId(uncPath);
_mockFileSystem.Path.Exists(uncPath).Returns(true);
// Act
bool result = _sut.Exists(pathId);
// Assert
result.Should().BeTrue();
_mockFileSystem.Path.Received(1).Exists(uncPath);
}
[Fact]
public void CombinePath_WithValidPathAndName_ShouldReturnCombinedPath()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Users\User");
string name = "Documents";
// Act
ErrorOr<FileSystemPathId> result = _sut.CombinePath(path, name);
// Assert
result.IsError.Should().BeFalse();
result.Value.Path.Should().Be(@"C:\Users\User\Documents\");
}
[Fact]
public void CombinePath_WithTrailingBackslashInPath_ShouldReturnCorrectlyCombinedPath()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Users\User\");
string name = "Documents";
// Act
ErrorOr<FileSystemPathId> result = _sut.CombinePath(path, name);
// Assert
result.IsError.Should().BeFalse();
result.Value.Path.Should().Be(@"C:\Users\User\Documents\");
}
[Fact]
public void CombinePath_WithLeadingBackslashInName_ShouldReturnCorrectlyCombinedPath()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Users\User");
string name = @"\Documents";
// Act
ErrorOr<FileSystemPathId> result = _sut.CombinePath(path, name);
// Assert
result.IsError.Should().BeFalse();
result.Value.Path.Should().Be(@"C:\Users\User\Documents\");
}
[Fact]
public void CombinePath_WithNullName_ShouldReturnError()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Users\User");
string name = null!;
// Act
ErrorOr<FileSystemPathId> result = _sut.CombinePath(path, name);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.FileManagement.NameCannotBeEmpty);
}
[Fact]
public void CombinePath_WithRootPath_ShouldReturnCorrectlyCombinedPath()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\");
string name = "Users";
// Act
ErrorOr<FileSystemPathId> result = _sut.CombinePath(path, name);
// Assert
result.IsError.Should().BeFalse();
result.Value.Path.Should().Be(@"C:\Users\");
}
[Fact]
public void CombinePath_WithUNCPath_ShouldReturnCorrectlyCombinedPath()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"\\server\share");
string name = "folder";
// Act
ErrorOr<FileSystemPathId> result = _sut.CombinePath(path, name);
// Assert
result.IsError.Should().BeFalse();
result.Value.Path.Should().Be(@"\\server\share\folder\");
}
[Fact]
public void ParsePath_WithValidWindowsPath_ShouldReturnCorrectPathSegments()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Users\User\Documents\file.txt");
// Act
ErrorOr<IEnumerable<PathSegment>> result = _sut.ParsePath(path);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().HaveCount(5);
result.Value.ElementAt(0).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("C:", false, true));
result.Value.ElementAt(1).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("Users", true, false));
result.Value.ElementAt(2).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("User", true, false));
result.Value.ElementAt(3).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("Documents", true, false));
result.Value.ElementAt(4).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("file.txt", false, false));
}
[Fact]
public void ParsePath_WithRootPath_ShouldReturnSingleRootSegment()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\");
// Act
ErrorOr<IEnumerable<PathSegment>> result = _sut.ParsePath(path);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().HaveCount(1);
result.Value.Single().Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("C:", false, true));
}
[Fact]
public void ParsePath_WithTrailingBackslash_ShouldTreatLastSegmentAsDirectory()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Users\User\Documents\");
// Act
ErrorOr<IEnumerable<PathSegment>> result = _sut.ParsePath(path);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().HaveCount(4);
result.Value.Last().Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("Documents", true, false));
}
[Fact]
public void ParsePath_WithRelativePath_ShouldReturnError()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"Users\User");
// Act
ErrorOr<IEnumerable<PathSegment>> result = _sut.ParsePath(path);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.FileManagement.InvalidPath);
}
[Fact]
public void ParsePath_WithPathContainingDots_ShouldParseCorrectly()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Users\User\file.with.dots.txt");
// Act
ErrorOr<IEnumerable<PathSegment>> result = _sut.ParsePath(path);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().HaveCount(4);
result.Value.Last().Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("file.with.dots.txt", false, false));
}
[Fact]
public void ParsePath_WithUNCPath_ShouldReturnCorrectPathSegments()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"\\server\share\folder\file.txt");
// Act
ErrorOr<IEnumerable<PathSegment>> result = _sut.ParsePath(path);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().HaveCount(5);
result.Value.ElementAt(0).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment(@"\\", false, true));
result.Value.ElementAt(1).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("server", true, false));
result.Value.ElementAt(2).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("share", true, false));
result.Value.ElementAt(3).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("folder", true, false));
result.Value.ElementAt(4).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("file.txt", false, false));
}
[Fact]
public void GoUpOneLevel_WithValidPath_ShouldReturnParentPath()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Users\User\Documents");
// Act
ErrorOr<IEnumerable<PathSegment>> result = _sut.GoUpOneLevel(path);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().HaveCount(3);
result.Value.ElementAt(0).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("C:", false, true));
result.Value.ElementAt(1).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("Users", true, false));
result.Value.ElementAt(2).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("User", true, false));
}
[Fact]
public void GoUpOneLevel_WithRootPath_ShouldReturnError()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\");
// Act
ErrorOr<IEnumerable<PathSegment>> result = _sut.GoUpOneLevel(path);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.FileManagement.CannotNavigateUp);
}
[Fact]
public void GoUpOneLevel_WithTrailingBackslash_ShouldReturnCorrectParentPath()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Users\User\");
// Act
ErrorOr<IEnumerable<PathSegment>> result = _sut.GoUpOneLevel(path);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().HaveCount(2);
result.Value.ElementAt(0).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("C:", false, true));
result.Value.ElementAt(1).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("Users", true, false));
}
[Fact]
public void GoUpOneLevel_WithInvalidPath_ShouldReturnError()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"invalid\path");
// Act
ErrorOr<IEnumerable<PathSegment>> result = _sut.GoUpOneLevel(path);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.FileManagement.InvalidPath);
}
[Fact]
public void GoUpOneLevel_WithSingleLevelPath_ShouldReturnRootPath()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Users");
// Act
ErrorOr<IEnumerable<PathSegment>> result = _sut.GoUpOneLevel(path);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().HaveCount(1);
result.Value.Single().Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("C:", false, true));
}
[Fact]
public void GoUpOneLevel_WithUNCPath_ShouldReturnParentPath()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"\\server\share\folder\subfolder");
// Act
ErrorOr<IEnumerable<PathSegment>> result = _sut.GoUpOneLevel(path);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().HaveCount(4);
result.Value.ElementAt(0).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment(@"\\", false, true));
result.Value.ElementAt(1).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("server", true, false));
result.Value.ElementAt(2).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("share", true, false));
result.Value.ElementAt(3).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("folder", true, false));
}
[Fact]
public void GoUpOneLevel_WithUNCRootPath_ShouldReturnError()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"\\server\share");
// Act
ErrorOr<IEnumerable<PathSegment>> result = _sut.GoUpOneLevel(path);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.FileManagement.CannotNavigateUp);
}
[Fact]
public void GoUpOneLevel_WithUNCPathWithOneFolder_ShouldReturnUNCRoot()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"\\server\share\folder");
// Act
ErrorOr<IEnumerable<PathSegment>> result = _sut.GoUpOneLevel(path);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().HaveCount(3);
result.Value.ElementAt(0).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment(@"\\", false, true));
result.Value.ElementAt(1).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("server", true, false));
result.Value.ElementAt(2).Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("share", true, false));
}
[Fact]
public void GoUpOneLevel_WithDriveRootAndBackslash_ShouldReturnError()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\");
// Act
ErrorOr<IEnumerable<PathSegment>> result = _sut.GoUpOneLevel(path);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.FileManagement.CannotNavigateUp);
}
[Fact]
public void GetInvalidPathCharsForPlatform_WhenCalled_ShouldReturnExpectedCharacters()
{
// Act
char[] result = _sut.GetInvalidPathCharsForPlatform();
// Assert
result.Should().BeEquivalentTo(['<', '>', '"', '/', '|', '?', '*' ]);
}
[Fact]
public void GetInvalidPathCharsForPlatform_WhenCalled_ShouldNotContainCertainCharacters()
{
// Act
char[] result = _sut.GetInvalidPathCharsForPlatform();
// Assert
result.Should().NotContain('\\');
result.Should().NotContain(':');
result.Should().NotContain('\0');
}
[Fact]
public void GetInvalidPathCharsForPlatform_WhenCalled_ShouldReturnSameResultOnMultipleCalls()
{
// Act
char[] result1 = _sut.GetInvalidPathCharsForPlatform();
char[] result2 = _sut.GetInvalidPathCharsForPlatform();
// Assert
result1.Should().BeEquivalentTo(result2);
}
[Fact]
public void GetPathRoot_WithValidWindowsPath_ShouldReturnRootSegment()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\Users\User\Documents");
// Act
ErrorOr<PathSegment> result = _sut.GetPathRoot(path);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("C:\\", true, true));
}
[Fact]
public void GetPathRoot_WithRootPath_ShouldReturnRootSegment()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\");
// Act
ErrorOr<PathSegment> result = _sut.GetPathRoot(path);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment("C:\\", true, true));
}
[Fact]
public void GetPathRoot_WithInvalidPath_ShouldReturnError()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"InvalidFolder");
// Act
ErrorOr<PathSegment> result = _sut.GetPathRoot(path);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.FileManagement.InvalidPath);
}
[Fact]
public void GetPathRoot_WithUNCPath_ShouldReturnUNCRootSegment()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"\\server\share\folder");
// Act
ErrorOr<PathSegment> result = _sut.GetPathRoot(path);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment(@"\\server\share\", true, false));
}
[Fact]
public void GetPathRoot_WithInvalidUNCPath_ShouldReturnError()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"\\");
// Act
ErrorOr<PathSegment> result = _sut.GetPathRoot(path);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.FileManagement.InvalidPath);
}
[Fact]
public void GetPathRoot_WithUNCPathWithoutShare_ShouldReturnError()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"\\server");
// Act
ErrorOr<PathSegment> result = _sut.GetPathRoot(path);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.FileManagement.InvalidPath);
}
[Fact]
public void GetPathRoot_WithNonDriveNonUNCPath_ShouldReturnError()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"InvalidPath");
// Act
ErrorOr<PathSegment> result = _sut.GetPathRoot(path);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.FileManagement.InvalidPath);
}
[Fact]
public void GetPathRoot_WithUNCPathMissingServerName_ShouldReturnError()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"\\");
// Act
ErrorOr<PathSegment> result = _sut.GetPathRoot(path);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.FileManagement.InvalidPath);
}
[Fact]
public void GetPathRoot_WithUNCPathWithoutThirdBackslash_ShouldReturnServerAndShare()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"\\server\share");
// Act
ErrorOr<PathSegment> result = _sut.GetPathRoot(path);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeEquivalentTo(_pathSegmentFixture.CreatePathSegment(@"\\server\share\", true, false));
}
[Fact]
public void GetPathRoot_WithNeitherUNCNorDrivePath_ShouldReturnError()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.CreateFileSystemPathId(@"invalid\path");
// Act
ErrorOr<PathSegment> result = _sut.GetPathRoot(path);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.FileManagement.InvalidPath);
}
#endregion
}
@@ -0,0 +1,12 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform;
#endregion
namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Strategies.Platform.Fixtures;
/// <summary>
/// Fixture interface for non existing platform context.
/// </summary>
public interface INonExistentPlatformContextFixture : IPlatformContext
{
}
@@ -0,0 +1,72 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Path;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform;
using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Strategies.Platform.Fixtures;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO.Abstractions;
#endregion
namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Strategies.Platform;
/// <summary>
/// Contains unit tests for the <see cref="PlatformContextFactory"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class PlatformContextFactoryTests
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly IServiceProvider _serviceProvider;
private readonly PlatformContextFactory _sut;
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="PlatformContextFactoryTests"/> class.
/// </summary>
public PlatformContextFactoryTests()
{
ServiceCollection services = new();
services.AddTransient<IWindowsPlatformContext, WindowsPlatformContext>();
services.AddTransient<IUnixPlatformContext, UnixPlatformContext>();
services.AddTransient<IUnixPathStrategy, UnixPathStrategy>();
services.AddTransient<IWindowsPathStrategy, WindowsPathStrategy>();
services.AddTransient<IFileSystem, FileSystem>();
_serviceProvider = services.BuildServiceProvider();
_sut = new PlatformContextFactory(_serviceProvider);
}
#endregion
#region ===================================================================== METHODS ===================================================================================
[Fact]
public void CreateStrategy_WhenWindowsServiceExists_ShouldReturnWindowsService()
{
// Act
IWindowsPlatformContext result = _sut.CreateStrategy<IWindowsPlatformContext>();
// Assert
result.Should().NotBeNull();
result.Should().BeOfType<WindowsPlatformContext>();
}
[Fact]
public void CreateStrategy_WhenUnixServiceExists_ShouldReturnUnixService()
{
// Act
IUnixPlatformContext result = _sut.CreateStrategy<IUnixPlatformContext>();
// Assert
result.Should().NotBeNull();
result.Should().BeOfType<UnixPlatformContext>();
}
[Fact]
public void CreateStrategy_WhenServiceDoesNotExist_ShouldThrowInvalidOperationException()
{
// Act & Assert
Assert.Throws<InvalidOperationException>(() => _sut.CreateStrategy<INonExistentPlatformContextFixture>());
}
#endregion
}
@@ -0,0 +1,159 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Contracts.Enums.FileSystem;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
#endregion
namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Strategies.Platform;
/// <summary>
/// Contains unit tests for the <see cref="PlatformContextManager"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class PlatformContextManagerTests
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly IPlatformContextFactory _mockPlatformContextFactory;
private PlatformContextManager? sut;
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="PlatformContextManagerTests"/> class.
/// </summary>
public PlatformContextManagerTests()
{
_mockPlatformContextFactory = Substitute.For<IPlatformContextFactory>();
}
#endregion
#region ===================================================================== METHODS ===================================================================================
[Fact]
public void GetCurrentContext_WhenNoContextSet_ShouldSetDefaultContext()
{
// Arrange
IWindowsPlatformContext mockWindowsContext = Substitute.For<IWindowsPlatformContext>();
_mockPlatformContextFactory.CreateStrategy<IWindowsPlatformContext>().Returns(mockWindowsContext);
IOperatingSystemInfo mockOsInfo = Substitute.For<IOperatingSystemInfo>();
mockOsInfo.IsOSPlatform(OSPlatform.Linux).Returns(false);
sut = new(_mockPlatformContextFactory, mockOsInfo);
// Act
IPlatformContext result = sut.GetCurrentContext();
// Assert
result.Should().Be(mockWindowsContext);
_mockPlatformContextFactory.Received(1).CreateStrategy<IWindowsPlatformContext>();
}
[Fact]
public void GetCurrentContext_WhenContextAlreadySet_ShouldReturnExistingContext()
{
// Arrange
IUnixPlatformContext mockUnixContext = Substitute.For<IUnixPlatformContext>();
_mockPlatformContextFactory.CreateStrategy<IUnixPlatformContext>().Returns(mockUnixContext);
IOperatingSystemInfo mockOsInfo = Substitute.For<IOperatingSystemInfo>();
sut = new(_mockPlatformContextFactory, mockOsInfo);
sut.SetCurrentPlatform(PlatformType.Unix);
// Act
IPlatformContext result = sut.GetCurrentContext();
// Assert
result.Should().Be(mockUnixContext);
_mockPlatformContextFactory.Received(1).CreateStrategy<IUnixPlatformContext>();
}
[Fact]
public void SetCurrentPlatform_WhenUnixPlatform_ShouldSetUnixContext()
{
// Arrange
IUnixPlatformContext mockUnixContext = Substitute.For<IUnixPlatformContext>();
_mockPlatformContextFactory.CreateStrategy<IUnixPlatformContext>().Returns(mockUnixContext);
IOperatingSystemInfo mockOsInfo = Substitute.For<IOperatingSystemInfo>();
mockOsInfo.IsOSPlatform(OSPlatform.Linux).Returns(true);
sut = new(_mockPlatformContextFactory, mockOsInfo);
// Act
sut.SetCurrentPlatform(PlatformType.Unix);
IPlatformContext result = sut.GetCurrentContext();
// Assert
result.Should().Be(mockUnixContext);
_mockPlatformContextFactory.Received(1).CreateStrategy<IUnixPlatformContext>();
}
[Fact]
public void SetCurrentPlatform_WhenWindowsPlatform_ShouldSetWindowsContext()
{
// Arrange
IWindowsPlatformContext mockWindowsContext = Substitute.For<IWindowsPlatformContext>();
_mockPlatformContextFactory.CreateStrategy<IWindowsPlatformContext>().Returns(mockWindowsContext);
IOperatingSystemInfo mockOsInfo = Substitute.For<IOperatingSystemInfo>();
mockOsInfo.IsOSPlatform(OSPlatform.Linux).Returns(false);
sut = new(_mockPlatformContextFactory, mockOsInfo);
// Act
sut.SetCurrentPlatform(PlatformType.Windows);
IPlatformContext result = sut.GetCurrentContext();
// Assert
result.Should().Be(mockWindowsContext);
_mockPlatformContextFactory.Received(1).CreateStrategy<IWindowsPlatformContext>();
}
[Fact]
public void SetCurrentPlatform_WhenUnsupportedPlatform_ShouldThrowArgumentException()
{
// Arrange
PlatformType unsupportedPlatform = (PlatformType)999; // An unsupported platform type
IOperatingSystemInfo mockOsInfo = Substitute.For<IOperatingSystemInfo>();
sut = new(_mockPlatformContextFactory, mockOsInfo);
// Act & Assert
Action act = () => sut.SetCurrentPlatform(unsupportedPlatform);
act.Should().Throw<ArgumentException>()
.WithMessage($"Unsupported platform type: {unsupportedPlatform}");
}
[Fact]
public void GetCurrentContext_WhenRunningOnLinux_ShouldSetUnixContextByDefault()
{
// Arrange
IUnixPlatformContext mockUnixContext = Substitute.For<IUnixPlatformContext>();
_mockPlatformContextFactory.CreateStrategy<IUnixPlatformContext>().Returns(mockUnixContext);
IOperatingSystemInfo mockOsInfo = Substitute.For<IOperatingSystemInfo>();
mockOsInfo.IsOSPlatform(OSPlatform.Linux).Returns(true);
sut = new(_mockPlatformContextFactory, mockOsInfo);
// Act
IPlatformContext result = sut.GetCurrentContext();
// Assert
result.Should().Be(mockUnixContext);
_mockPlatformContextFactory.Received(1).CreateStrategy<IUnixPlatformContext>();
}
[Fact]
public void GetCurrentContext_WhenRunningOnWindows_ShouldSetWindowsContextByDefault()
{
// Arrange
IWindowsPlatformContext mockWindowsContext = Substitute.For<IWindowsPlatformContext>();
_mockPlatformContextFactory.CreateStrategy<IWindowsPlatformContext>().Returns(mockWindowsContext);
IOperatingSystemInfo mockOsInfo = Substitute.For<IOperatingSystemInfo>();
mockOsInfo.IsOSPlatform(OSPlatform.Linux).Returns(false);
sut = new(_mockPlatformContextFactory, mockOsInfo);
// Act
IPlatformContext result = sut.GetCurrentContext();
// Assert
result.Should().Be(mockWindowsContext);
_mockPlatformContextFactory.Received(1).CreateStrategy<IWindowsPlatformContext>();
}
#endregion
}
@@ -0,0 +1,121 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Contracts.Enums.FileSystem;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Path;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform;
using NSubstitute;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Strategies.Platform;
/// <summary>
/// Contains unit tests for the <see cref="WindowsPlatformContext"/> and <see cref="UnixPlatformContext"/> classes.
/// </summary>
[ExcludeFromCodeCoverage]
public class PlatformContextTests
{
#region ===================================================================== METHODS ===================================================================================
[Fact]
public void WindowsPlatformContext_Constructor_ShouldSetPropertiesCorrectly()
{
// Arrange
IWindowsPathStrategy mockWindowsPathStrategy = Substitute.For<IWindowsPathStrategy>();
// Act
WindowsPlatformContext windowsPlatformContext = new(mockWindowsPathStrategy);
// Assert
windowsPlatformContext.Platform.Should().Be(PlatformType.Windows);
windowsPlatformContext.PathStrategy.Should().Be(mockWindowsPathStrategy);
}
[Fact]
public void UnixPlatformContext_Constructor_ShouldSetPropertiesCorrectly()
{
// Arrange
IUnixPathStrategy mockUnixPathStrategy = Substitute.For<IUnixPathStrategy>();
// Act
UnixPlatformContext unixPlatformContext = new(mockUnixPathStrategy);
// Assert
unixPlatformContext.Platform.Should().Be(PlatformType.Unix);
unixPlatformContext.PathStrategy.Should().Be(mockUnixPathStrategy);
}
[Fact]
public void WindowsPlatformContext_ShouldImplementIWindowsPlatformContext()
{
// Arrange
IWindowsPathStrategy mockWindowsPathStrategy = Substitute.For<IWindowsPathStrategy>();
// Act
WindowsPlatformContext windowsPlatformContext = new(mockWindowsPathStrategy);
// Assert
windowsPlatformContext.Should().BeAssignableTo<IWindowsPlatformContext>();
}
[Fact]
public void UnixPlatformContext_ShouldImplementIUnixPlatformContext()
{
// Arrange
IUnixPathStrategy mockUnixPathStrategy = Substitute.For<IUnixPathStrategy>();
// Act
UnixPlatformContext unixPlatformContext = new(mockUnixPathStrategy);
// Assert
unixPlatformContext.Should().BeAssignableTo<IUnixPlatformContext>();
}
[Fact]
public void WindowsPlatformContext_PathStrategy_ShouldBeReadOnly()
{
// Arrange
IWindowsPathStrategy mockWindowsPathStrategy = Substitute.For<IWindowsPathStrategy>();
WindowsPlatformContext windowsPlatformContext = new(mockWindowsPathStrategy);
// Act & Assert
windowsPlatformContext.GetType().GetProperty(nameof(WindowsPlatformContext.PathStrategy))!
.SetMethod.Should().BeNull();
}
[Fact]
public void UnixPlatformContext_PathStrategy_ShouldBeReadOnly()
{
// Arrange
IUnixPathStrategy mockUnixPathStrategy = Substitute.For<IUnixPathStrategy>();
UnixPlatformContext unixPlatformContext = new(mockUnixPathStrategy);
// Act & Assert
unixPlatformContext.GetType().GetProperty(nameof(UnixPlatformContext.PathStrategy))!
.SetMethod.Should().BeNull();
}
[Fact]
public void WindowsPlatformContext_Platform_ShouldBeReadOnly()
{
// Arrange
IWindowsPathStrategy mockWindowsPathStrategy = Substitute.For<IWindowsPathStrategy>();
WindowsPlatformContext windowsPlatformContext = new(mockWindowsPathStrategy);
// Act & Assert
windowsPlatformContext.GetType().GetProperty(nameof(WindowsPlatformContext.Platform))!
.SetMethod.Should().BeNull();
}
[Fact]
public void UnixPlatformContext_Platform_ShouldBeReadOnly()
{
// Arrange
IUnixPathStrategy mockUnixPathStrategy = Substitute.For<IUnixPathStrategy>();
UnixPlatformContext unixPlatformContext = new(mockUnixPathStrategy);
// Act & Assert
unixPlatformContext.GetType().GetProperty(nameof(UnixPlatformContext.Platform))!
.SetMethod.Should().BeNull();
}
#endregion
}
@@ -0,0 +1,150 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FluentAssertions;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects;
using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects.Fixtures;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects;
/// <summary>
/// Contains unit tests for the <see cref="FileSystemPathId"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class FileSystemPathIdTests
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly FileSystemPathIdFixture _fileSystemPathIdFixture;
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="FileSystemPathIdTests"/> class.
/// </summary>
public FileSystemPathIdTests()
{
_fileSystemPathIdFixture = new FileSystemPathIdFixture();
}
#endregion
#region ===================================================================== METHODS ===================================================================================
[Fact]
public void Create_WithValidPath_ShouldReturnFileSystemPathId()
{
// Arrange
string validPath = @"C:\TestDir\file.txt";
// Act
ErrorOr<FileSystemPathId> result = FileSystemPathId.Create(validPath);
// Assert
result.IsError.Should().BeFalse();
result.Value.Path.Should().Be(validPath);
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData(" ")]
public void Create_WithInvalidPath_ShouldReturnError(string invalidPath)
{
// Act
ErrorOr<FileSystemPathId> result = FileSystemPathId.Create(invalidPath);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.FileManagement.InvalidPath);
}
[Fact]
public void Equals_WithSamePath_ShouldReturnTrue()
{
// Arrange
string path = @"C:\TestDir\file.txt";
FileSystemPathId id1 = _fileSystemPathIdFixture.CreateFileSystemPathId(path);
FileSystemPathId id2 = _fileSystemPathIdFixture.CreateFileSystemPathId(path);
// Act
bool result = id1.Equals(id2);
// Assert
result.Should().BeTrue();
}
[Fact]
public void Equals_WithDifferentPath_ShouldReturnFalse()
{
// Arrange
FileSystemPathId id1 = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir\file1.txt");
FileSystemPathId id2 = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir\file2.txt");
// Act
bool result = id1.Equals(id2);
// Assert
result.Should().BeFalse();
}
[Fact]
public void GetHashCode_WithSamePath_ShouldReturnSameHashCode()
{
// Arrange
string path = @"C:\TestDir\file.txt";
FileSystemPathId id1 = _fileSystemPathIdFixture.CreateFileSystemPathId(path);
FileSystemPathId id2 = _fileSystemPathIdFixture.CreateFileSystemPathId(path);
// Act
int hashCode1 = id1.GetHashCode();
int hashCode2 = id2.GetHashCode();
// Assert
hashCode1.Should().Be(hashCode2);
}
[Fact]
public void GetHashCode_WithDifferentPath_ShouldReturnDifferentHashCode()
{
// Arrange
FileSystemPathId id1 = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir\file1.txt");
FileSystemPathId id2 = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir\file2.txt");
// Act
int hashCode1 = id1.GetHashCode();
int hashCode2 = id2.GetHashCode();
// Assert
hashCode1.Should().NotBe(hashCode2);
}
[Fact]
public void EqualityOperator_WithSamePath_ShouldReturnTrue()
{
// Arrange
string path = @"C:\TestDir\file.txt";
FileSystemPathId id1 = _fileSystemPathIdFixture.CreateFileSystemPathId(path);
FileSystemPathId id2 = _fileSystemPathIdFixture.CreateFileSystemPathId(path);
// Act
bool result = id1 == id2;
// Assert
result.Should().BeTrue();
}
[Fact]
public void InequalityOperator_WithDifferentPath_ShouldReturnTrue()
{
// Arrange
FileSystemPathId id1 = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir\file1.txt");
FileSystemPathId id2 = _fileSystemPathIdFixture.CreateFileSystemPathId(@"C:\TestDir\file2.txt");
// Act
bool result = id1 != id2;
// Assert
result.Should().BeTrue();
}
#endregion
}
@@ -0,0 +1,48 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using ErrorOr;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects.Fixtures;
/// <summary>
/// Fixture class for the <see cref="FileSystemPathId"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class FileSystemPathIdFixture
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly Faker _faker;
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="FileSystemPathIdFixture"/> class.
/// </summary>
public FileSystemPathIdFixture()
{
_faker = new Faker();
}
#endregion
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Creates a random valid <see cref="FileSystemPathId"/>.
/// </summary>
/// <param name="path">The path of the file system path element.</param>
/// <returns>The created <see cref="FileSystemPathId"/>.</returns>
public FileSystemPathId CreateFileSystemPathId(string? path = null)
{
path ??= _faker.System.FilePath();
ErrorOr<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(path);
if (fileSystemPathIdResult.IsError)
throw new InvalidOperationException("Failed to create FileSystemPathId: " + string.Join(", ", fileSystemPathIdResult.Errors));
return fileSystemPathIdResult.Value;
}
#endregion
}
@@ -0,0 +1,64 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using ErrorOr;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects.Fixtures;
/// <summary>
/// Fixture class for the <see cref="PathSegment"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class PathSegmentFixture
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly Faker _faker;
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="PathSegmentFixture"/> class.
/// </summary>
public PathSegmentFixture()
{
_faker = new Faker();
}
#endregion
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Creates a random valid <see cref="PathSegment"/>.
/// </summary>
/// <returns>The created <see cref="PathSegment"/>.</returns>
public PathSegment CreatePathSegment(
string? name = null,
bool? isDirectory = null,
bool? isDrive = null)
{
name ??= _faker.System.FileName();
isDirectory ??= true;
isDrive ??= false;
ErrorOr<PathSegment> pathResult = PathSegment.Create(name, isDirectory.Value, isDrive.Value);
if (pathResult.IsError)
throw new InvalidOperationException("Failed to create PathSegment: " + string.Join(", ", pathResult.Errors));
return pathResult.Value;
}
/// <summary>
/// Creates a list of <see cref="PathSegment"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<PathSegment> CreateMany(int count = 3)
{
return Enumerable.Range(0, count).Select(_ => CreatePathSegment()).ToList();
}
#endregion
}
@@ -0,0 +1,84 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using ErrorOr;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects.Fixtures;
/// <summary>
/// Fixture class for the <see cref="StreamInfo"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class StreamInfoFixture
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly Faker _faker;
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="StreamInfoFixture"/> class.
/// </summary>
public StreamInfoFixture()
{
_faker = new Faker();
}
#endregion
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Creates a random valid <see cref="StreamInfo"/>.
/// </summary>
/// <param name="streamId">Optional. The unique identifier for the stream. If not provided, a default value may be used.</param>
/// <param name="mimeType">Optional. The MIME type of the stream (e.g., video/mp4, audio/mpeg). If not provided, a default MIME type may be used.</param>
/// <param name="bitrate">Optional. The bitrate of the stream in kbps. If not provided, a default value may be used.</param>
/// <param name="codec">Optional. The codec used for the stream (e.g., H.264, AAC). If not provided, a default codec may be used.</param>
/// <param name="resolution">Optional. The video resolution (e.g., 1920x1080). If not provided, a default resolution may be used.</param>
/// <param name="frameRate">Optional. The frame rate of the video stream in frames per second (fps). If not provided, a default frame rate may be used.</param>
/// <param name="sampleRate">Optional. The sample rate of the audio stream in Hz. If not provided, a default sample rate may be used.</param>
/// <param name="channels">Optional. The number of audio channels (e.g., 2 for stereo, 6 for 5.1 surround). If not provided, a default channel count may be used.</param>
/// <returns>The created <see cref="StreamInfo"/>.</returns>
public StreamInfo CreateStreamInfo(
string? streamId = null,
string? mimeType = null,
int? bitrate = null,
string? codec = null,
Optional<string>? resolution = null,
Optional<float>? frameRate = null,
Optional<int>? sampleRate = null,
Optional<int>? channels = null)
{
streamId ??= _faker.Random.AlphaNumeric(10);
mimeType ??= _faker.System.MimeType();
bitrate ??= _faker.Random.Number(1, 10000);
codec ??= _faker.Random.Word();
resolution ??= Optional<string>.FromNullable(_faker.Random.Bool() ? $"{_faker.Random.Number(100, 4000)}x{_faker.Random.Number(100, 4000)}" : null);
frameRate ??= Optional<float>.FromNullable(_faker.Random.Bool() ? (float?)_faker.Random.Float(1, 120) : null);
sampleRate ??= Optional<int>.FromNullable(_faker.Random.Bool() ? (int?)_faker.Random.Number(8000, 192000) : null);
channels ??= Optional<int>.FromNullable(_faker.Random.Bool() ? (int?)_faker.Random.Number(1, 8) : null);
ErrorOr<StreamInfo> streamInfoResult = StreamInfo.Create(
streamId, mimeType, bitrate.Value, codec, resolution.Value, frameRate.Value, sampleRate.Value, channels.Value);
if (streamInfoResult.IsError)
throw new InvalidOperationException("Failed to create StreamInfo: " + string.Join(", ", streamInfoResult.Errors));
return streamInfoResult.Value;
}
/// <summary>
/// Creates a list of <see cref="StreamInfo"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<StreamInfo> CreateMany(int count = 3)
{
return Enumerable.Range(0, count).Select(_ => CreateStreamInfo()).ToList();
}
#endregion
}
@@ -0,0 +1,57 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Contracts.Enums.PhotoLibrary;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects.Fixtures;
/// <summary>
/// Fixture class for the <see cref="Thumbnail"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ThumbnailFixture
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly Faker _faker;
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="ThumbnailFixture"/> class.
/// </summary>
public ThumbnailFixture()
{
_faker = new Faker();
}
#endregion
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Creates a random valid <see cref="Thumbnail"/>.
/// </summary>
/// <param name="type">Optional. The <see cref="ImageType"/> of the thumbnail. If not provided, a random image type is selected.</param>
/// <param name="bytes">Optional. The byte array representing the image data. If not provided, a random 1KB byte array is generated.</param>
/// <returns>A newly created <see cref="Thumbnail"/> instance.</returns>
public Thumbnail CreateThumbnail(ImageType? type = null, byte[]? bytes = null)
{
type ??= _faker.PickRandom<ImageType>();
bytes ??= _faker.Random.Bytes(1024); // Generate 1KB of random bytes
return new Thumbnail(type.Value, bytes);
}
/// <summary>
/// Creates a list of <see cref="Thumbnail"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<Thumbnail> CreateMany(int count = 3)
{
return Enumerable.Range(0, count).Select(_ => CreateThumbnail()).ToList();
}
#endregion
}
@@ -0,0 +1,151 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FluentAssertions;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects;
using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects.Fixtures;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects;
/// <summary>
/// Contains unit tests for the <see cref="PathSegment"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class PathSegmentTests
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly PathSegmentFixture _pathSegmentFixture;
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="PathSegmentTests"/> class.
/// </summary>
public PathSegmentTests()
{
_pathSegmentFixture = new PathSegmentFixture();
}
#endregion
#region ===================================================================== METHODS ===================================================================================
[Fact]
public void Create_WithValidInput_ShouldReturnPathSegment()
{
// Arrange
string name = "testFolder";
bool isDirectory = true;
bool isDrive = false;
// Act
ErrorOr<PathSegment> result = PathSegment.Create(name, isDirectory, isDrive);
// Assert
result.IsError.Should().BeFalse();
result.Value.Name.Should().Be(name);
result.Value.IsDirectory.Should().Be(isDirectory);
result.Value.IsDrive.Should().Be(isDrive);
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData(" ")]
public void Create_WithInvalidName_ShouldReturnError(string invalidName)
{
// Act
ErrorOr<PathSegment> result = PathSegment.Create(invalidName, true, false);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.FileManagement.NameCannotBeEmpty);
}
[Fact]
public void Equals_WithSameProperties_ShouldReturnTrue()
{
// Arrange
PathSegment segment1 = _pathSegmentFixture.CreatePathSegment("folder", true, false);
PathSegment segment2 = _pathSegmentFixture.CreatePathSegment("folder", true, false);
// Act
bool result = segment1.Equals(segment2);
// Assert
result.Should().BeTrue();
}
[Fact]
public void Equals_WithDifferentProperties_ShouldReturnFalse()
{
// Arrange
PathSegment segment1 = _pathSegmentFixture.CreatePathSegment("folder1", true, false);
PathSegment segment2 = _pathSegmentFixture.CreatePathSegment("folder2", true, false);
// Act
bool result = segment1.Equals(segment2);
// Assert
result.Should().BeFalse();
}
[Fact]
public void GetHashCode_WithSameProperties_ShouldReturnSameHashCode()
{
// Arrange
PathSegment segment1 = _pathSegmentFixture.CreatePathSegment("folder", true, false);
PathSegment segment2 = _pathSegmentFixture.CreatePathSegment("folder", true, false);
// Act
int hashCode1 = segment1.GetHashCode();
int hashCode2 = segment2.GetHashCode();
// Assert
hashCode1.Should().Be(hashCode2);
}
[Fact]
public void GetHashCode_WithDifferentProperties_ShouldReturnDifferentHashCode()
{
// Arrange
PathSegment segment1 = _pathSegmentFixture.CreatePathSegment("folder1", true, false);
PathSegment segment2 = _pathSegmentFixture.CreatePathSegment("folder2", true, false);
// Act
int hashCode1 = segment1.GetHashCode();
int hashCode2 = segment2.GetHashCode();
// Assert
hashCode1.Should().NotBe(hashCode2);
}
[Fact]
public void EqualityOperator_WithSameProperties_ShouldReturnTrue()
{
// Arrange
PathSegment segment1 = _pathSegmentFixture.CreatePathSegment("folder", true, false);
PathSegment segment2 = _pathSegmentFixture.CreatePathSegment("folder", true, false);
// Act
bool result = segment1 == segment2;
// Assert
result.Should().BeTrue();
}
[Fact]
public void InequalityOperator_WithDifferentProperties_ShouldReturnTrue()
{
// Arrange
PathSegment segment1 = _pathSegmentFixture.CreatePathSegment("folder1", true, false);
PathSegment segment2 = _pathSegmentFixture.CreatePathSegment("folder2", true, false);
// Act
bool result = segment1 != segment2;
// Assert
result.Should().BeTrue();
}
#endregion
}
@@ -0,0 +1,186 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FluentAssertions;
using Lumina.Contracts.Enums.FileSystem;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Environment;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Strategies.Platform;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects;
using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.Entities.Fixtures;
using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects.Fixtures;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects;
/// <summary>
/// Contains unit tests for the <see cref="StreamInfo"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class StreamInfoTests
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly StreamInfoFixture _streamInfoFixture;
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="StreamInfoTests"/> class.
/// </summary>
public StreamInfoTests()
{
_streamInfoFixture = new StreamInfoFixture();
}
#endregion
#region ===================================================================== METHODS ===================================================================================
[Fact]
public void Create_WithValidInput_ShouldReturnStreamInfo()
{
// Arrange
string streamId = "testStream";
string mimeType = "video/mp4";
int bitrate = 1000;
string codec = "h264";
Optional<string> resolution = Optional<string>.Some("1920x1080");
Optional<float> frameRate = Optional<float>.Some(30.0f);
Optional<int> sampleRate = Optional<int>.Some(44100);
Optional<int> channels = Optional<int>.Some(2);
// Act
ErrorOr<StreamInfo> result = StreamInfo.Create(streamId, mimeType, bitrate, codec, resolution, frameRate, sampleRate, channels);
// Assert
result.IsError.Should().BeFalse();
result.Value.StreamId.Should().Be(streamId);
result.Value.MimeType.Should().Be(mimeType);
result.Value.Bitrate.Should().Be(bitrate);
result.Value.Codec.Should().Be(codec);
result.Value.Resolution.Should().Be(resolution);
result.Value.FrameRate.Should().Be(frameRate);
result.Value.SampleRate.Should().Be(sampleRate);
result.Value.Channels.Should().Be(channels);
}
[Fact]
public void Create_WithNullStreamId_ShouldReturnError()
{
// Arrange
string? streamId = null;
string mimeType = "video/mp4";
int bitrate = 1000;
string codec = "h264";
// Act
ErrorOr<StreamInfo> result = StreamInfo.Create(streamId!, mimeType, bitrate, codec, Optional<string>.None(), Optional<float>.None(), Optional<int>.None(), Optional<int>.None());
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.FileManagement.StreamIdCannotBeEmpty);
}
[Fact]
public void Create_WithNullCodec_ShouldReturnError()
{
// Arrange
string streamId = "testStream";
string mimeType = "video/mp4";
int bitrate = 1000;
string? codec = null;
// Act
ErrorOr<StreamInfo> result = StreamInfo.Create(streamId, mimeType, bitrate, codec!, Optional<string>.None(), Optional<float>.None(), Optional<int>.None(), Optional<int>.None());
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.FileManagement.CodecCannotBeEmpty);
}
[Fact]
public void Create_WithNonPositiveBitrate_ShouldReturnError()
{
// Arrange
string streamId = "testStream";
string mimeType = "video/mp4";
int bitrate = 0;
string codec = "h264";
// Act
ErrorOr<StreamInfo> result = StreamInfo.Create(streamId, mimeType, bitrate, codec, Optional<string>.None(), Optional<float>.None(), Optional<int>.None(), Optional<int>.None());
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.FileManagement.BitrateMustBeAPositiveNumber);
}
[Fact]
public void Equals_WithSameProperties_ShouldReturnTrue()
{
// Arrange
StreamInfo info1 = _streamInfoFixture.CreateStreamInfo();
StreamInfo info2 = _streamInfoFixture.CreateStreamInfo(
info1.StreamId, info1.MimeType, info1.Bitrate, info1.Codec,
info1.Resolution, info1.FrameRate, info1.SampleRate, info1.Channels);
// Act
bool result = info1.Equals(info2);
// Assert
result.Should().BeTrue();
}
[Fact]
public void Equals_WithDifferentProperties_ShouldReturnFalse()
{
// Arrange
StreamInfo info1 = _streamInfoFixture.CreateStreamInfo();
StreamInfo info2 = _streamInfoFixture.CreateStreamInfo();
// Act
bool result = info1.Equals(info2);
// Assert
result.Should().BeFalse();
}
[Fact]
public void GetHashCode_WithSameProperties_ShouldReturnSameHashCode()
{
// Arrange
StreamInfo info1 = _streamInfoFixture.CreateStreamInfo();
StreamInfo info2 = _streamInfoFixture.CreateStreamInfo(
info1.StreamId, info1.MimeType, info1.Bitrate, info1.Codec,
info1.Resolution, info1.FrameRate, info1.SampleRate, info1.Channels);
// Act
int hashCode1 = info1.GetHashCode();
int hashCode2 = info2.GetHashCode();
// Assert
hashCode1.Should().Be(hashCode2);
}
[Fact]
public void GetHashCode_WithDifferentProperties_ShouldReturnDifferentHashCode()
{
// Arrange
StreamInfo info1 = _streamInfoFixture.CreateStreamInfo();
StreamInfo info2 = _streamInfoFixture.CreateStreamInfo();
// Act
int hashCode1 = info1.GetHashCode();
int hashCode2 = info2.GetHashCode();
// Assert
hashCode1.Should().NotBe(hashCode2);
}
#endregion
}
@@ -0,0 +1,137 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Contracts.Enums.PhotoLibrary;
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects;
using Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects.Fixtures;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Domain.UnitTests.Core.Aggregates.FileManagementAggregate.ValueObjects;
/// <summary>
/// Contains unit tests for the <see cref="Thumbnail"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ThumbnailTests
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly ThumbnailFixture _thumbnailFixture;
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="ThumbnailTests"/> class.
/// </summary>
public ThumbnailTests()
{
_thumbnailFixture = new ThumbnailFixture();
}
#endregion
#region ===================================================================== METHODS ===================================================================================
[Fact]
public void Constructor_ShouldSetPropertiesCorrectly()
{
// Arrange
ImageType type = ImageType.PNG;
byte[] bytes = [1, 2, 3, 4, 5];
// Act
Thumbnail thumbnail = new(type, bytes);
// Assert
thumbnail.Type.Should().Be(type);
thumbnail.Bytes.Should().BeEquivalentTo(bytes);
}
[Fact]
public void Equals_WithSameProperties_ShouldReturnTrue()
{
// Arrange
Thumbnail thumbnail1 = _thumbnailFixture.CreateThumbnail();
Thumbnail thumbnail2 = new(thumbnail1.Type, thumbnail1.Bytes);
// Act
bool result = thumbnail1.Equals(thumbnail2);
// Assert
result.Should().BeTrue();
}
[Fact]
public void Equals_WithDifferentType_ShouldReturnFalse()
{
// Arrange
Thumbnail thumbnail1 = _thumbnailFixture.CreateThumbnail(ImageType.PNG);
Thumbnail thumbnail2 = _thumbnailFixture.CreateThumbnail(ImageType.JPEG, thumbnail1.Bytes);
// Act
bool result = thumbnail1.Equals(thumbnail2);
// Assert
result.Should().BeFalse();
}
[Fact]
public void Equals_WithDifferentBytes_ShouldReturnFalse()
{
// Arrange
Thumbnail thumbnail1 = _thumbnailFixture.CreateThumbnail();
Thumbnail thumbnail2 = _thumbnailFixture.CreateThumbnail(thumbnail1.Type);
// Act
bool result = thumbnail1.Equals(thumbnail2);
// Assert
result.Should().BeFalse();
}
[Fact]
public void GetHashCode_WithSameProperties_ShouldReturnSameHashCode()
{
// Arrange
Thumbnail thumbnail1 = _thumbnailFixture.CreateThumbnail();
Thumbnail thumbnail2 = new(thumbnail1.Type, thumbnail1.Bytes);
// Act
int hashCode1 = thumbnail1.GetHashCode();
int hashCode2 = thumbnail2.GetHashCode();
// Assert
hashCode1.Should().Be(hashCode2);
}
[Fact]
public void GetHashCode_WithDifferentProperties_ShouldReturnDifferentHashCode()
{
// Arrange
Thumbnail thumbnail1 = _thumbnailFixture.CreateThumbnail();
Thumbnail thumbnail2 = _thumbnailFixture.CreateThumbnail();
// Act
int hashCode1 = thumbnail1.GetHashCode();
int hashCode2 = thumbnail2.GetHashCode();
// Assert
hashCode1.Should().NotBe(hashCode2);
}
[Fact]
public void GetEqualityComponents_ShouldReturnTypeAndBytes()
{
// Arrange
Thumbnail thumbnail = _thumbnailFixture.CreateThumbnail();
// Act
List<object> components = thumbnail.GetEqualityComponents().ToList();
// Assert
components.Should().HaveCount(2);
components[0].Should().Be(thumbnail.Type);
components[1].Should().BeEquivalentTo(thumbnail.Bytes);
}
#endregion
}
@@ -11,7 +11,9 @@
<ItemGroup>
<PackageReference Include="AutoFixture.AutoNSubstitute" Version="4.18.1" />
<PackageReference Include="System.IO.Abstractions.TestingHelpers" Version="21.0.29" />
<PackageReference Include="AutoFixture.Xunit2" Version="4.18.1" />
<PackageReference Include="Bogus" Version="35.6.0" />
<PackageReference Include="coverlet.collector" Version="6.0.0" />
<PackageReference Include="FluentAssertions" Version="6.12.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />