Replaces MVC with FastEndpoints in Lumina.Presentation.Api

This commit is contained in:
BinaryAlley committed 2024-10-23 21:34:10 +03:00
1 parent b1a20716df
commit c7b8bc2f1c
519 files changed
+15329 -8539

No files matched your search

@@ -0,0 +1,110 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using ErrorOr;
using Lumina.Contracts.Enums.FileSystem;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate;
using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Fixtures;
/// <summary>
/// Fixture class for the <see cref="Directory"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DirectoryFixture
{
private readonly Faker _faker;
/// <summary>
/// Initializes a new instance of the <see cref="DirectoryFixture"/> class.
/// </summary>
public DirectoryFixture()
{
_faker = new Faker();
}
/// <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 Directory instance.</returns>
/// <exception cref="InvalidOperationException">Thrown if the 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);
}
}
@@ -0,0 +1,46 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Contracts.Responses.FileSystemManagement.Directories;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Fixtures;
/// <summary>
/// Fixture class for the <see cref="DirectoryResponse"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DirectoryResponseFixture
{
private readonly Faker _faker = new();
private readonly FileSystemItemModelFixture _fileSystemItemModelFixture = new();
/// <summary>
/// Creates a random valid <see cref="DirectoryResponse"/>.
/// </summary>
/// <param name="itemCount">The number of children elements to create.</param>
/// <returns>The created <see cref="DirectoryResponse"/>.</returns>
public DirectoryResponse Create(int itemCount = 3)
{
return new DirectoryResponse(
_faker.System.FilePath(),
_faker.System.FileName(),
_faker.Date.Past(),
_faker.Date.Recent(),
_fileSystemItemModelFixture.CreateMany(itemCount)
);
}
/// <summary>
/// Creates a list of <see cref="DirectoryResponse"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <param name="itemCount">The number of children elemens to create for each element.</param>
/// <returns>The created list.</returns>
public List<DirectoryResponse> CreateMany(int count = 3, int itemCount = 3)
{
return Enumerable.Range(0, count).Select(_ => Create(itemCount)).ToList();
}
}
@@ -0,0 +1,42 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Contracts.Entities.FileSystemManagement;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Fixtures;
/// <summary>
/// Fixture class for the <see cref="FileSystemItemEntity"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class FileSystemItemModelFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="FileSystemItemEntity"/>.
/// </summary>
/// <returns>The created <see cref="FileSystemItemEntity"/>.</returns>
public FileSystemItemEntity Create()
{
return new FileSystemItemEntity(
_faker.System.FilePath(),
_faker.System.FileName(),
_faker.Date.Past(),
_faker.Date.Recent()
);
}
/// <summary>
/// Creates a list of <see cref="FileSystemItemEntity"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<FileSystemItemEntity> CreateMany(int count = 3)
{
return Enumerable.Range(0, count).Select(_ => Create()).ToList();
}
}
@@ -0,0 +1,58 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Contracts.Enums.FileSystem;
using Lumina.Contracts.Responses.FileSystemManagement.Common;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Fixtures;
/// <summary>
/// Fixture class for the <see cref="FileSystemTreeNodeResponse"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class FileSystemTreeNodeResponseFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a single <see cref="FileSystemTreeNodeResponse"/> with a nested structure.
/// </summary>
/// <param name="currentDepth">The current depth in the tree structure. Default is 0 (root level).</param>
/// <param name="maxDepth">The maximum depth of the tree structure. Default is 2.</param>
/// <param name="maxChildren">The maximum number of children for each node. Default is 3.</param>
/// <returns>A <see cref="FileSystemTreeNodeResponse"/> with a nested structure.</returns>
public FileSystemTreeNodeResponse Create(int currentDepth = 0, int maxDepth = 2, int maxChildren = 3)
{
FileSystemTreeNodeResponse response = new()
{
Path = _faker.System.FilePath(),
Name = _faker.System.FileName(),
ItemType = FileSystemItemType.Directory,
IsExpanded = _faker.Random.Bool(),
ChildrenLoaded = true,
Children = []
};
if (currentDepth < maxDepth)
{
int childCount = _faker.Random.Int(1, maxChildren);
for (int i = 0; i < childCount; i++)
response.Children.Add(Create(currentDepth + 1, maxDepth, maxChildren));
}
return response;
}
/// <summary>
/// Creates a list of <see cref="FileSystemTreeNodeResponse"/> objects, each with a nested structure.
/// </summary>
/// <param name="count">The number of root-level nodes to create. Default is 2.</param>
/// <param name="maxDepth">The maximum depth of the tree structure for each root node. Default is 2.</param>
/// <param name="maxChildren">The maximum number of children for each node. Default is 3.</param>
/// <returns>A list of <see cref="FileSystemTreeNodeResponse"/> objects with nested structures.</returns>
public List<FileSystemTreeNodeResponse> CreateMany(int count = 2, int maxDepth = 2, int maxChildren = 3)
{
return Enumerable.Range(0, count).Select(_ => Create(0, maxDepth, maxChildren)).ToList();
}
}
@@ -0,0 +1,30 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDirectories;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Queries.GetDirectories.Fixtures;
/// <summary>
/// Fixture class for the <see cref="GetDirectoriesQuery"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDirectoriesQueryFixture
{
/// <summary>
/// Creates a random valid query to get directories.
/// </summary>
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
/// <returns>The created query to get directories.</returns>
public static GetDirectoriesQuery CreateGetDirectoriesQuery(bool includeHiddenElements = false)
{
return new Faker<GetDirectoriesQuery>()
.CustomInstantiator(f => new GetDirectoriesQuery(
default!,
default
))
.RuleFor(x => x.Path, f => f.System.DirectoryPath())
.RuleFor(x => x.IncludeHiddenElements, f => includeHiddenElements);
}
}
@@ -0,0 +1,148 @@
#region ========================================================================= USING =====================================================================================
using AutoFixture;
using AutoFixture.AutoNSubstitute;
using ErrorOr;
using FluentAssertions;
using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDirectories;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Fixtures;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Queries.GetDirectories.Fixtures;
using Lumina.Contracts.Responses.FileSystemManagement.Directories;
using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities;
using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Queries.GetDirectories;
/// <summary>
/// Contains unit tests for the <see cref="GetDirectoriesQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDirectoriesQueryHandlerTests
{
private readonly IFixture _fixture;
private readonly IDirectoryService _mockDirectoryService;
private readonly GetDirectoriesQueryHandler _sut;
private readonly DirectoryFixture _directoryFixture;
/// <summary>
/// Initializes a new instance of the <see cref="GetDirectoriesQueryHandlerTests"/> class.
/// </summary>
public GetDirectoriesQueryHandlerTests()
{
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
_mockDirectoryService = Substitute.For<IDirectoryService>();
_sut = new GetDirectoriesQueryHandler(_mockDirectoryService);
_directoryFixture = new DirectoryFixture();
}
[Fact]
public async Task Handle_WhenCalledWithValidQueryWithoutFilesIncluded_ShouldReturnSuccessResult()
{
// Arrange
GetDirectoriesQuery getDirectoriesQuery = GetDirectoriesQueryFixture.CreateGetDirectoriesQuery(false);
IEnumerable<Directory> directories = _directoryFixture.CreateMany();
_mockDirectoryService.GetSubdirectories(getDirectoriesQuery.Path!, getDirectoriesQuery.IncludeHiddenElements)
.Returns(ErrorOrFactory.From(directories));
// Act
ErrorOr<IEnumerable<DirectoryResponse>> result = await _sut.Handle(getDirectoriesQuery, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeAssignableTo<IEnumerable<DirectoryResponse>>();
result.Value.Should().HaveCount(directories.Count());
List<DirectoryResponse> resultList = result.Value.ToList();
List<Directory> directoriesList = directories.ToList();
for (int i = 0; i < resultList.Count; i++)
{
resultList[i].Path.Should().Be(directoriesList[i].Id.Path);
resultList[i].Name.Should().Be(directoriesList[i].Name);
resultList[i].DateCreated.Should().Be(directoriesList[i].DateCreated.Value);
resultList[i].DateModified.Should().Be(directoriesList[i].DateModified.Value);
resultList[i].Items.Should().BeEmpty(); // since files are not included
}
_mockDirectoryService.Received(1).GetSubdirectories(getDirectoriesQuery.Path!, getDirectoriesQuery.IncludeHiddenElements);
}
[Fact]
public async Task Handle_WhenCalledWithValidQueryWithFilesIncluded_ShouldReturnSuccessResult()
{
// Arrange
GetDirectoriesQuery getDirectoriesQuery = GetDirectoriesQueryFixture.CreateGetDirectoriesQuery(true);
IEnumerable<Directory> directories = _directoryFixture.CreateMany();
_mockDirectoryService.GetSubdirectories(getDirectoriesQuery.Path!, getDirectoriesQuery.IncludeHiddenElements)
.Returns(ErrorOrFactory.From(directories));
// Act
ErrorOr<IEnumerable<DirectoryResponse>> result = await _sut.Handle(getDirectoriesQuery, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeAssignableTo<IEnumerable<DirectoryResponse>>();
result.Value.Should().HaveCount(directories.Count());
List<DirectoryResponse> resultList = result.Value.ToList();
List<Directory> directoriesList = directories.ToList();
for (int i = 0; i < resultList.Count; i++)
{
resultList[i].Path.Should().Be(directoriesList[i].Id.Path);
resultList[i].Name.Should().Be(directoriesList[i].Name);
resultList[i].DateCreated.Should().Be(directoriesList[i].DateCreated.Value);
resultList[i].DateModified.Should().Be(directoriesList[i].DateModified.Value);
resultList[i].Items.Should().HaveCount(directoriesList[i].Items.Count);
}
_mockDirectoryService.Received(1).GetSubdirectories(getDirectoriesQuery.Path!, getDirectoriesQuery.IncludeHiddenElements);
}
[Fact]
public async Task Handle_WhenDirectoryServiceReturnsError_ShouldReturnFailureResult()
{
// Arrange
GetDirectoriesQuery query = _fixture.Create<GetDirectoriesQuery>();
Error error = Error.Failure("DirectoryService.Error", "An error occurred");
_mockDirectoryService.GetSubdirectories(query.Path!, query.IncludeHiddenElements)
.Returns(error);
// Act
ErrorOr<IEnumerable<DirectoryResponse>> result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(error);
_mockDirectoryService.Received(1).GetSubdirectories(query.Path!, query.IncludeHiddenElements);
}
[Fact]
public async Task Handle_WhenDirectoryServiceReturnsEmptyList_ShouldReturnEmptySuccessResult()
{
// Arrange
GetDirectoriesQuery query = _fixture.Create<GetDirectoriesQuery>();
ErrorOr<IEnumerable<Directory>> emptyList = ErrorOrFactory.From(Enumerable.Empty<Directory>());
_mockDirectoryService.GetSubdirectories(query.Path!, query.IncludeHiddenElements)
.Returns(emptyList);
// Act
ErrorOr<IEnumerable<DirectoryResponse>> result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeEmpty();
_mockDirectoryService.Received(1).GetSubdirectories(query.Path!, query.IncludeHiddenElements);
}
}
@@ -0,0 +1,113 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation.TestHelper;
using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDirectories;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Queries.GetDirectories.Fixtures;
using System.Diagnostics.CodeAnalysis;
using Lumina.Domain.Common.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Queries.GetDirectories;
/// <summary>
/// Contains unit tests for the <see cref="GetDirectoriesQueryValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDirectoriesQueryValidatorTests
{
private readonly GetDirectoriesQueryValidator _validator;
/// <summary>
/// Initializes a new instance of the <see cref="GetDirectoriesQueryValidatorTests"/> class.
/// </summary>
public GetDirectoriesQueryValidatorTests()
{
_validator = new GetDirectoriesQueryValidator();
}
[Fact]
public void Validate_WhenPathIsNull_ShouldHaveValidationError()
{
// Arrange
GetDirectoriesQuery query = GetDirectoriesQueryFixture.CreateGetDirectoriesQuery();
query = query with { Path = null! };
// Act
TestValidationResult<GetDirectoriesQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationErrorFor(x => x.Path)
.WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
}
[Fact]
public void Validate_WhenPathIsEmpty_ShouldHaveValidationError()
{
// Arrange
GetDirectoriesQuery query = GetDirectoriesQueryFixture.CreateGetDirectoriesQuery();
query = query with { Path = string.Empty };
// Act
TestValidationResult<GetDirectoriesQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationErrorFor(x => x.Path)
.WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
}
[Fact]
public void Validate_WhenPathIsWhitespace_ShouldHaveValidationError()
{
// Arrange
GetDirectoriesQuery query = GetDirectoriesQueryFixture.CreateGetDirectoriesQuery();
query = query with { Path = " " };
// Act
TestValidationResult<GetDirectoriesQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationErrorFor(x => x.Path)
.WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
}
[Fact]
public void Validate_WhenPathIsValid_ShouldNotHaveValidationError()
{
// Arrange
GetDirectoriesQuery query = GetDirectoriesQueryFixture.CreateGetDirectoriesQuery();
query = query with { Path = "/valid/path" };
// Act
TestValidationResult<GetDirectoriesQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationErrorFor(x => x.Path);
}
[Fact]
public void Validate_WhenIncludeHiddenElementsIsTrue_ShouldNotHaveValidationError()
{
// Arrange
GetDirectoriesQuery query = GetDirectoriesQueryFixture.CreateGetDirectoriesQuery();
query = query with { IncludeHiddenElements = true };
// Act
TestValidationResult<GetDirectoriesQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationErrorFor(x => x.IncludeHiddenElements);
}
[Fact]
public void Validate_WhenIncludeHiddenElementsIsFalse_ShouldNotHaveValidationError()
{
// Arrange
GetDirectoriesQuery query = GetDirectoriesQueryFixture.CreateGetDirectoriesQuery();
query = query with { IncludeHiddenElements = false };
// Act
TestValidationResult<GetDirectoriesQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationErrorFor(x => x.IncludeHiddenElements);
}
}
@@ -0,0 +1,33 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDirectoryTree;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Queries.GetDirectoryTree.Fixtures;
/// <summary>
/// Fixture class for the <see cref="GetDirectoryTreeQuery"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDirectoryTreeQueryFixture
{
/// <summary>
/// Creates a random valid query to get directory tree.
/// </summary>
/// <param name="includeFiles">Whether to include file system files or not.</param>
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
/// <returns>The created query to get directory tree.</returns>
public static GetDirectoryTreeQuery CreateGetDirectoryTreeQuery(bool includeFiles = false, bool includeHiddenElements = false)
{
return new Faker<GetDirectoryTreeQuery>()
.CustomInstantiator(f => new GetDirectoryTreeQuery(
default!,
default,
default
))
.RuleFor(x => x.Path, f => f.System.DirectoryPath())
.RuleFor(x => x.IncludeFiles, f => includeFiles)
.RuleFor(x => x.IncludeHiddenElements, f => includeHiddenElements);
}
}
@@ -0,0 +1,383 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FluentAssertions;
using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDirectoryTree;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Fixtures;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Queries.GetDirectoryTree.Fixtures;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Fixtures;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Fixtures;
using Lumina.Contracts.Responses.FileSystemManagement.Common;
using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate;
using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities;
using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services;
using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects;
using NSubstitute;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Queries.GetDirectoryTree;
/// <summary>
/// Contains unit tests for the <see cref="GetDirectoryTreeQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDirectoryTreeQueryHandlerTests
{
private readonly IDriveService _mockDriveService;
private readonly IDirectoryService _mockDirectoryService;
private readonly IFileService _mockFileService;
private readonly IPathService _mockPathService;
private readonly GetDirectoryTreeQueryHandler _sut;
private readonly DirectoryFixture _directoryFixture;
private readonly PathSegmentFixture _pathSegmentFixture;
private readonly FileFixture _fileFixture;
/// <summary>
/// Initializes a new instance of the <see cref="GetDirectoryTreeQueryHandlerTests"/> class.
/// </summary>
public GetDirectoryTreeQueryHandlerTests()
{
_mockDriveService = Substitute.For<IDriveService>();
_mockDirectoryService = Substitute.For<IDirectoryService>();
_mockFileService = Substitute.For<IFileService>();
_mockPathService = Substitute.For<IPathService>();
_sut = new GetDirectoryTreeQueryHandler(_mockDriveService, _mockDirectoryService, _mockFileService, _mockPathService);
_directoryFixture = new DirectoryFixture();
_pathSegmentFixture = new PathSegmentFixture();
_fileFixture = new FileFixture();
}
[Fact]
public async Task Handle_WhenCalledWithValidQueryAndNoIncludeFiles_ShouldReturnSuccessResult()
{
// Arrange
GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery(false, true);
// Create a drive that matches what the implementation expects
string drivePath = "C:\\";
IEnumerable<FileSystemItem> drives =
[
WindowsRootItem.Create(drivePath, "C:").Value
];
// Ensure the first path segment matches the drive path
PathSegment firstPathSegment = _pathSegmentFixture.CreatePathSegment(name: "C:", isDrive: true);
List<PathSegment> otherPathSegments = _pathSegmentFixture.CreateMany(2);
IEnumerable<PathSegment> pathSegments = new[] { firstPathSegment }.Concat(otherPathSegments);
IEnumerable<Directory> subdirectories = _directoryFixture.CreateMany(2);
IEnumerable<File> files = _fileFixture.CreateMany(2);
_mockDriveService.GetDrives().Returns(ErrorOrFactory.From(drives));
_mockPathService.ParsePath(query.Path!).Returns(ErrorOrFactory.From(pathSegments));
_mockPathService.CombinePath(Arg.Is<string>(x => true), Arg.Is<string>(y => true)).Returns(callInfo => $"{callInfo.ArgAt<string>(0)}\\{callInfo.ArgAt<string>(1)}");
_mockDirectoryService.GetSubdirectories(Arg.Any<string>(), query.IncludeHiddenElements).Returns(ErrorOrFactory.From(subdirectories));
_mockFileService.GetFiles(Arg.Any<string>(), query.IncludeHiddenElements).Returns(ErrorOrFactory.From(files));
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().NotBeEmpty();
result.Value.First().Children.Should().NotBeEmpty();
_mockDriveService.Received(1).GetDrives();
_mockPathService.Received(1).ParsePath(query.Path!);
_mockDirectoryService.Received(1).GetSubdirectories(Arg.Any<string>(), query.IncludeHiddenElements);
_mockFileService.Received(0).GetFiles(Arg.Any<string>(), query.IncludeHiddenElements);
}
[Fact]
public async Task Handle_WhenCalledWithValidQueryAndIncludeFiles_ShouldReturnSuccessResult()
{
// Arrange
GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery(true, true);
// Create a drive that matches what the implementation expects
string drivePath = "C:\\";
IEnumerable<FileSystemItem> drives =
[
WindowsRootItem.Create(drivePath, "C:").Value
];
// Ensure the first path segment matches the drive path
PathSegment firstPathSegment = _pathSegmentFixture.CreatePathSegment(name: "C:", isDrive: true);
List<PathSegment> otherPathSegments = _pathSegmentFixture.CreateMany(2);
IEnumerable<PathSegment> pathSegments = new[] { firstPathSegment }.Concat(otherPathSegments);
IEnumerable<Directory> subdirectories = _directoryFixture.CreateMany(2);
IEnumerable<File> files = _fileFixture.CreateMany(2);
_mockDriveService.GetDrives().Returns(ErrorOrFactory.From(drives));
_mockPathService.ParsePath(query.Path!).Returns(ErrorOrFactory.From(pathSegments));
_mockPathService.CombinePath(Arg.Is<string>(x => true), Arg.Is<string>(y => true)).Returns(callInfo => $"{callInfo.ArgAt<string>(0)}\\{callInfo.ArgAt<string>(1)}");
_mockDirectoryService.GetSubdirectories(Arg.Any<string>(), query.IncludeHiddenElements).Returns(ErrorOrFactory.From(subdirectories));
_mockFileService.GetFiles(Arg.Any<string>(), query.IncludeHiddenElements).Returns(ErrorOrFactory.From(files));
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().NotBeEmpty();
result.Value.First().Children.Should().NotBeEmpty();
_mockDriveService.Received(1).GetDrives();
_mockPathService.Received(1).ParsePath(query.Path!);
_mockDirectoryService.Received(1).GetSubdirectories(Arg.Any<string>(), query.IncludeHiddenElements);
_mockFileService.Received(1).GetFiles(Arg.Any<string>(), query.IncludeHiddenElements);
}
[Fact]
public async Task Handle_WhenGetDrivesReturnsError_ShouldReturnFailureResult()
{
// Arrange
GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery();
Error error = Error.Failure("DriveService.Error", "An error occurred");
_mockDriveService.GetDrives().Returns(error);
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(error);
_mockDriveService.Received(1).GetDrives();
}
[Fact]
public async Task Handle_WhenParsePathReturnsError_ShouldReturnFailureResult()
{
// Arrange
GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery();
IEnumerable<FileSystemItem> drives =
[
WindowsRootItem.Create("C:\\", "Local Disk").Value
];
Error error = Error.Failure("PathService.Error", "An error occurred");
_mockDriveService.GetDrives().Returns(ErrorOrFactory.From(drives));
_mockPathService.ParsePath(query.Path!).Returns(error);
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(error);
_mockDriveService.Received(1).GetDrives();
_mockPathService.Received(1).ParsePath(query.Path!);
}
[Fact]
public async Task Handle_WhenCombinePathReturnsError_ShouldReturnFailureResult()
{
// Arrange
GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery();
IEnumerable<FileSystemItem> drives =
[
WindowsRootItem.Create("C:\\", "C:").Value
];
PathSegment firstPathSegment = _pathSegmentFixture.CreatePathSegment(name: "C:", isDrive: true);
IEnumerable<PathSegment> pathSegments = new[] { firstPathSegment }.Concat(_pathSegmentFixture.CreateMany(2));
Error error = Error.Failure("PathService.Error", "An error occurred");
_mockDriveService.GetDrives().Returns(ErrorOrFactory.From(drives));
_mockPathService.ParsePath(query.Path!).Returns(ErrorOrFactory.From(pathSegments));
_mockPathService.CombinePath(Arg.Any<string>(), Arg.Any<string>()).Returns(error);
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(error);
_mockDriveService.Received(1).GetDrives();
_mockPathService.Received(1).ParsePath(query.Path!);
_mockPathService.Received(1).CombinePath(Arg.Any<string>(), Arg.Any<string>());
}
[Fact]
public async Task Handle_WhenGetSubdirectoriesReturnsError_ShouldReturnFailureResult()
{
// Arrange
GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery();
IEnumerable<FileSystemItem> drives =
[
WindowsRootItem.Create("C:\\", "C:").Value
];
PathSegment firstPathSegment = _pathSegmentFixture.CreatePathSegment(name: "C:", isDrive: true);
IEnumerable<PathSegment> pathSegments = new[] { firstPathSegment }.Concat(_pathSegmentFixture.CreateMany(2));
Error error = Error.Failure("DirectoryService.Error", "An error occurred");
_mockDriveService.GetDrives().Returns(ErrorOrFactory.From(drives));
_mockPathService.ParsePath(query.Path!).Returns(ErrorOrFactory.From(pathSegments));
_mockPathService.CombinePath(Arg.Is<string>(x => true), Arg.Is<string>(y => true)).Returns(callInfo => $"{callInfo.ArgAt<string>(0)}\\{callInfo.ArgAt<string>(1)}");
_mockDirectoryService.GetSubdirectories(Arg.Any<string>(), query.IncludeHiddenElements).Returns(error);
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(error);
_mockDriveService.Received(1).GetDrives();
_mockPathService.Received(1).ParsePath(query.Path!);
_mockDirectoryService.Received(1).GetSubdirectories(Arg.Any<string>(), query.IncludeHiddenElements);
}
[Fact]
public async Task Handle_WhenGetFilesReturnsError_ShouldReturnFailureResult()
{
// Arrange
GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery(true);
IEnumerable<FileSystemItem> drives =
[
WindowsRootItem.Create("C:\\", "C:").Value
];
PathSegment firstPathSegment = _pathSegmentFixture.CreatePathSegment(name: "C:", isDrive: true);
IEnumerable<PathSegment> pathSegments = new[] { firstPathSegment }.Concat(_pathSegmentFixture.CreateMany(2));
IEnumerable<Directory> subdirectories = _directoryFixture.CreateMany(2);
Error error = Error.Failure("FileService.Error", "An error occurred");
_mockDriveService.GetDrives().Returns(ErrorOrFactory.From(drives));
_mockPathService.ParsePath(query.Path!).Returns(ErrorOrFactory.From(pathSegments));
_mockPathService.CombinePath(Arg.Is<string>(x => true), Arg.Is<string>(y => true)).Returns(callInfo => $"{callInfo.ArgAt<string>(0)}\\{callInfo.ArgAt<string>(1)}");
_mockDirectoryService.GetSubdirectories(Arg.Any<string>(), query.IncludeHiddenElements).Returns(ErrorOrFactory.From(subdirectories));
_mockFileService.GetFiles(Arg.Any<string>(), query.IncludeHiddenElements).Returns(error);
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(error);
_mockDriveService.Received(1).GetDrives();
_mockPathService.Received(1).ParsePath(query.Path!);
_mockDirectoryService.Received(1).GetSubdirectories(Arg.Any<string>(), query.IncludeHiddenElements);
_mockFileService.Received(1).GetFiles(Arg.Any<string>(), query.IncludeHiddenElements);
}
[Fact]
public async Task Handle_WhenPathOnlyContainsRoot_ShouldReturnOnlyRootNode()
{
// Arrange
GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery();
query = query with { Path = "C:" };
IEnumerable<FileSystemItem> drives = [WindowsRootItem.Create("C:\\", "C:").Value];
PathSegment rootSegment = _pathSegmentFixture.CreatePathSegment(name: "C:", isDrive: true);
_mockDriveService.GetDrives().Returns(ErrorOrFactory.From(drives));
_mockPathService.ParsePath(query.Path).Returns(ErrorOrFactory.From((IEnumerable<PathSegment>)[rootSegment]));
_mockDirectoryService.GetSubdirectories(Arg.Any<string>(), Arg.Any<bool>())
.Returns(ErrorOrFactory.From(Enumerable.Empty<Directory>()));
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().HaveCount(1);
result.Value.First().Name.Should().Be("C:");
result.Value.First().Children.Should().BeEmpty();
}
[Fact]
public async Task Handle_WhenPathHasManySegments_ShouldCreateCorrectTreeStructure()
{
// Arrange
GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery();
IEnumerable<FileSystemItem> drives = [WindowsRootItem.Create("C:\\", "C:").Value];
List<PathSegment> pathSegments =
[
_pathSegmentFixture.CreatePathSegment(name: "C:", isDrive: true),
_pathSegmentFixture.CreatePathSegment(name: "Users"),
_pathSegmentFixture.CreatePathSegment(name: "Username"),
_pathSegmentFixture.CreatePathSegment(name: "Documents"),
_pathSegmentFixture.CreatePathSegment(name: "Projects"),
_pathSegmentFixture.CreatePathSegment(name: "MyProject")
];
_mockDriveService.GetDrives().Returns(ErrorOrFactory.From(drives));
_mockPathService.ParsePath(query.Path!).Returns(ErrorOrFactory.From((IEnumerable<PathSegment>)pathSegments));
_mockPathService.Exists(Arg.Any<string>(), Arg.Any<bool>()).Returns(true);
_mockPathService.CombinePath(Arg.Any<string>(), Arg.Any<string>())
.Returns(callInfo => $"{callInfo.ArgAt<string>(0)}\\{callInfo.ArgAt<string>(1)}");
_mockDirectoryService.GetSubdirectories(Arg.Any<string>(), Arg.Any<bool>())
.Returns(ErrorOrFactory.From(Enumerable.Empty<Directory>()));
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().HaveCount(1);
FileSystemTreeNodeResponse root = result.Value.First();
root.Name.Should().Be("C:");
root.Children.Should().HaveCount(1);
root.Children.First().Name.Should().Be("Users");
root.Children.First().Children.First().Name.Should().Be("Username");
root.Children.First().Children.First().Children.First().Name.Should().Be("Documents");
root.Children.First().Children.First().Children.First().Children.First().Name.Should().Be("Projects");
root.Children.First().Children.First().Children.First().Children.First().Children.First().Name.Should().Be("MyProject");
}
[Fact]
public async Task Handle_WhenPathContainsSpecialCharacters_ShouldHandleCorrectly()
{
// Arrange
GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery();
IEnumerable<FileSystemItem> drives = [WindowsRootItem.Create("C:\\", "C:").Value];
List<PathSegment> pathSegments =
[
_pathSegmentFixture.CreatePathSegment(name: "C:", isDrive: true),
_pathSegmentFixture.CreatePathSegment(name: "Program Files"),
_pathSegmentFixture.CreatePathSegment(name: "My Awesome App!"),
_pathSegmentFixture.CreatePathSegment(name: "Data Files")
];
_mockDriveService.GetDrives().Returns(ErrorOrFactory.From(drives));
_mockPathService.Exists(Arg.Any<string>(), Arg.Any<bool>()).Returns(true);
_mockPathService.ParsePath(query.Path!).Returns(ErrorOrFactory.From((IEnumerable<PathSegment>)pathSegments));
_mockPathService.CombinePath(Arg.Any<string>(), Arg.Any<string>())
.Returns(callInfo => $"{callInfo.ArgAt<string>(0)}\\{callInfo.ArgAt<string>(1)}");
_mockDirectoryService.GetSubdirectories(Arg.Any<string>(), Arg.Any<bool>())
.Returns(ErrorOrFactory.From(Enumerable.Empty<Directory>()));
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().HaveCount(1);
FileSystemTreeNodeResponse root = result.Value.First();
root.Children.First().Name.Should().Be("Program Files");
root.Children.First().Children.First().Name.Should().Be("My Awesome App!");
}
[Fact]
public async Task Handle_WhenIncludeHiddenElementsIsFalse_ShouldNotIncludeHiddenItems()
{
// Arrange
GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery(includeHiddenElements: false);
IEnumerable<FileSystemItem> drives = [WindowsRootItem.Create("C:\\", "C:").Value];
PathSegment rootSegment = _pathSegmentFixture.CreatePathSegment(name: "C:", isDrive: true);
_mockDriveService.GetDrives().Returns(ErrorOrFactory.From(drives));
_mockPathService.ParsePath(query.Path!).Returns(ErrorOrFactory.From((IEnumerable<PathSegment>)[rootSegment]));
IEnumerable<Directory> visibleDirectories = _directoryFixture.CreateMany(2);
_mockDirectoryService.GetSubdirectories(Arg.Any<string>(), false).Returns(ErrorOrFactory.From(visibleDirectories));
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.First().Children.Should().HaveCount(2);
_mockDirectoryService.Received(1).GetSubdirectories(Arg.Any<string>(), false);
}
}
@@ -0,0 +1,141 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation.TestHelper;
using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDirectoryTree;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Queries.GetDirectoryTree.Fixtures;
using Lumina.Domain.Common.Errors;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Queries.GetDirectoryTree;
/// <summary>
/// Contains unit tests for the <see cref="GetDirectoryTreeQueryValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDirectoryTreeQueryValidatorTests
{
private readonly GetDirectoryTreeQueryValidator _validator;
/// <summary>
/// Initializes a new instance of the <see cref="GetDirectoryTreeQueryValidatorTests"/> class.
/// </summary>
public GetDirectoryTreeQueryValidatorTests()
{
_validator = new GetDirectoryTreeQueryValidator();
}
[Fact]
public void Validate_WhenPathIsNull_ShouldHaveValidationError()
{
// Arrange
GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery();
query = query with { Path = null! };
// Act
TestValidationResult<GetDirectoryTreeQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationErrorFor(x => x.Path)
.WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
}
[Fact]
public void Validate_WhenPathIsEmpty_ShouldHaveValidationError()
{
// Arrange
GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery();
query = query with { Path = string.Empty };
// Act
TestValidationResult<GetDirectoryTreeQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationErrorFor(x => x.Path)
.WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
}
[Fact]
public void Validate_WhenPathIsWhitespace_ShouldHaveValidationError()
{
// Arrange
GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery();
query = query with { Path = " " };
// Act
TestValidationResult<GetDirectoryTreeQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationErrorFor(x => x.Path)
.WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
}
[Fact]
public void Validate_WhenPathIsValid_ShouldNotHaveValidationError()
{
// Arrange
GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery();
query = query with { Path = "/valid/path" };
// Act
TestValidationResult<GetDirectoryTreeQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationErrorFor(x => x.Path);
}
[Fact]
public void Validate_WhenIncludeHiddenElementsIsTrue_ShouldNotHaveValidationError()
{
// Arrange
GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery();
query = query with { IncludeHiddenElements = true };
// Act
TestValidationResult<GetDirectoryTreeQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationErrorFor(x => x.IncludeHiddenElements);
}
[Fact]
public void Validate_WhenIncludeHiddenElementsIsFalse_ShouldNotHaveValidationError()
{
// Arrange
GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery();
query = query with { IncludeHiddenElements = false };
// Act
TestValidationResult<GetDirectoryTreeQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationErrorFor(x => x.IncludeHiddenElements);
}
[Fact]
public void Validate_WhenIncludeFilesIsTrue_ShouldNotHaveValidationError()
{
// Arrange
GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery();
query = query with { IncludeFiles = true };
// Act
TestValidationResult<GetDirectoryTreeQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationErrorFor(x => x.IncludeFiles);
}
[Fact]
public void Validate_WhenIncludeFilesIsFalse_ShouldNotHaveValidationError()
{
// Arrange
GetDirectoryTreeQuery query = GetDirectoryTreeQueryFixture.CreateGetDirectoryTreeQuery();
query = query with { IncludeFiles = false };
// Act
TestValidationResult<GetDirectoryTreeQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationErrorFor(x => x.IncludeFiles);
}
}
@@ -0,0 +1,30 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetTreeDirectories;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Queries.GetTreeDirectories.Fixtures;
/// <summary>
/// Fixture class for the <see cref="GetTreeDirectoriesQuery"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetTreeDirectoriesQueryFixture
{
/// <summary>
/// Creates a random valid query to get tree directories.
/// </summary>
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
/// <returns>The created query to get tree directory.</returns>
public static GetTreeDirectoriesQuery CreateGetTreeDirectoryQuery(bool includeHiddenElements = false)
{
return new Faker<GetTreeDirectoriesQuery>()
.CustomInstantiator(f => new GetTreeDirectoriesQuery(
default!,
default
))
.RuleFor(x => x.Path, f => f.System.DirectoryPath())
.RuleFor(x => x.IncludeHiddenElements, f => includeHiddenElements);
}
}
@@ -0,0 +1,232 @@
#region ========================================================================= USING =====================================================================================
using AutoFixture;
using AutoFixture.AutoNSubstitute;
using ErrorOr;
using FluentAssertions;
using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetTreeDirectories;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Fixtures;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Queries.GetTreeDirectories.Fixtures;
using Lumina.Contracts.Enums.FileSystem;
using Lumina.Contracts.Responses.FileSystemManagement.Common;
using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate;
using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities;
using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services;
using NSubstitute;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Queries.GetTreeDirectories;
/// <summary>
/// Contains unit tests for the <see cref="GetTreeDirectoriesQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetTreeDirectoriesQueryHandlerTests
{
private readonly IFixture _fixture;
private readonly IDirectoryService _mockDirectoryService;
private readonly GetTreeDirectoriesQueryHandler _sut;
private readonly DirectoryFixture _directoryFixture;
/// <summary>
/// Initializes a new instance of the <see cref="GetTreeDirectoriesQueryHandlerTests"/> class.
/// </summary>
public GetTreeDirectoriesQueryHandlerTests()
{
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
_mockDirectoryService = Substitute.For<IDirectoryService>();
_sut = new GetTreeDirectoriesQueryHandler(_mockDirectoryService);
_directoryFixture = new DirectoryFixture();
}
[Fact]
public async Task Handle_WhenCalledWithValidQueryWithoutFilesIncluded_ShouldReturnSuccessResult()
{
// Arrange
GetTreeDirectoriesQuery getDirectoriesQuery = GetTreeDirectoriesQueryFixture.CreateGetTreeDirectoryQuery(false);
IEnumerable<Directory> directories = _directoryFixture.CreateMany();
_mockDirectoryService.GetSubdirectories(getDirectoriesQuery.Path!, getDirectoriesQuery.IncludeHiddenElements)
.Returns(ErrorOrFactory.From(directories));
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sut.Handle(getDirectoriesQuery, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeAssignableTo<IEnumerable<FileSystemTreeNodeResponse>>();
result.Value.Should().HaveCount(directories.Count());
List<FileSystemTreeNodeResponse> resultList = result.Value.ToList();
List<Directory> directoriesList = directories.ToList();
for (int i = 0; i < resultList.Count; i++)
{
resultList[i].Path.Should().Be(directoriesList[i].Id.Path);
resultList[i].Name.Should().Be(directoriesList[i].Name);
resultList[i].ItemType.Should().Be(FileSystemItemType.Directory);
resultList[i].IsExpanded.Should().BeFalse();
resultList[i].ChildrenLoaded.Should().BeFalse();
resultList[i].Children.Should().BeEmpty();
}
_mockDirectoryService.Received(1).GetSubdirectories(getDirectoriesQuery.Path!, getDirectoriesQuery.IncludeHiddenElements);
}
[Fact]
public async Task Handle_WhenCalledWithValidQueryWithFilesIncluded_ShouldReturnSuccessResult()
{
// Arrange
GetTreeDirectoriesQuery getDirectoriesQuery = GetTreeDirectoriesQueryFixture.CreateGetTreeDirectoryQuery(true);
IEnumerable<Directory> directories = _directoryFixture.CreateManyNested();
_mockDirectoryService.GetSubdirectories(getDirectoriesQuery.Path!, getDirectoriesQuery.IncludeHiddenElements)
.Returns(ErrorOrFactory.From(directories));
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sut.Handle(getDirectoriesQuery, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeAssignableTo<IEnumerable<FileSystemTreeNodeResponse>>();
result.Value.Should().HaveCount(directories.Count());
List<FileSystemTreeNodeResponse> resultList = result.Value.ToList();
List<Directory> directoriesList = directories.ToList();
for (int i = 0; i < resultList.Count; i++)
{
FileSystemTreeNodeResponse response = resultList[i];
Directory directory = directoriesList[i];
response.Path.Should().Be(directory.Id.Path);
response.Name.Should().Be(directory.Name);
response.ItemType.Should().Be(FileSystemItemType.Directory);
response.IsExpanded.Should().BeFalse();
response.ChildrenLoaded.Should().BeFalse();
response.Children.Should().HaveCount(directory.Items.Count);
List<FileSystemTreeNodeResponse> childResponses = [.. response.Children];
List<FileSystemItem> directoryItems = [.. directory.Items];
for (int j = 0; j < childResponses.Count; j++)
{
FileSystemTreeNodeResponse childResponse = childResponses[j];
FileSystemItem item = directoryItems[j];
childResponse.Path.Should().Be(item.Id.Path);
childResponse.Name.Should().Be(item.Name);
childResponse.ItemType.Should().Be(item.Type);
childResponse.IsExpanded.Should().BeFalse();
childResponse.ChildrenLoaded.Should().BeFalse();
if (item is Directory)
childResponse.Children.Should().NotBeNull();
else
childResponse.Children.Should().BeEmpty();
}
}
_mockDirectoryService.Received(1).GetSubdirectories(getDirectoriesQuery.Path!, getDirectoriesQuery.IncludeHiddenElements);
}
[Fact]
public async Task Handle_WhenDirectoryServiceReturnsError_ShouldReturnFailureResult()
{
// Arrange
GetTreeDirectoriesQuery query = GetTreeDirectoriesQueryFixture.CreateGetTreeDirectoryQuery();
Error error = Error.Failure("DirectoryService.Error", "An error occurred");
_mockDirectoryService.GetSubdirectories(query.Path!, query.IncludeHiddenElements)
.Returns(error);
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(error);
_mockDirectoryService.Received(1).GetSubdirectories(query.Path!, query.IncludeHiddenElements);
}
[Fact]
public async Task Handle_WhenDirectoryServiceReturnsEmptyList_ShouldReturnEmptySuccessResult()
{
// Arrange
GetTreeDirectoriesQuery query = _fixture.Create<GetTreeDirectoriesQuery>();
ErrorOr<IEnumerable<Directory>> emptyList = ErrorOrFactory.From(Enumerable.Empty<Directory>());
_mockDirectoryService.GetSubdirectories(query.Path!, query.IncludeHiddenElements)
.Returns(emptyList);
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeEmpty();
_mockDirectoryService.Received(1).GetSubdirectories(query.Path!, query.IncludeHiddenElements);
}
[Fact]
public async Task Handle_WhenCalledWithNestedDirectories_ShouldReturnCorrectlyNestedResponse()
{
// Arrange
GetTreeDirectoriesQuery query = GetTreeDirectoriesQueryFixture.CreateGetTreeDirectoryQuery(true);
IEnumerable<Directory> nestedDirectories = _directoryFixture.CreateManyNested(2, 2, 2);
_mockDirectoryService.GetSubdirectories(query.Path!, query.IncludeHiddenElements)
.Returns(ErrorOrFactory.From(nestedDirectories));
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeAssignableTo<IEnumerable<FileSystemTreeNodeResponse>>();
result.Value.Should().HaveCount(2); // top level directories
List<FileSystemTreeNodeResponse> resultList = result.Value.ToList();
List<Directory> directoriesList = nestedDirectories.ToList();
for (int i = 0; i < resultList.Count; i++)
{
FileSystemTreeNodeResponse response = resultList[i];
Directory directory = directoriesList[i];
response.Path.Should().Be(directory.Id.Path);
response.Name.Should().Be(directory.Name);
response.ItemType.Should().Be(FileSystemItemType.Directory);
response.IsExpanded.Should().BeFalse();
response.ChildrenLoaded.Should().BeFalse();
response.Children.Should().HaveCount(directory.Items.Count);
// check first level of children
for (int j = 0; j < response.Children.Count; j++)
{
FileSystemTreeNodeResponse childResponse = response.Children[j];
FileSystemItem childItem = directory.Items.ElementAt(j);
childResponse.Path.Should().Be(childItem.Id.Path);
childResponse.Name.Should().Be(childItem.Name);
childResponse.ItemType.Should().Be(childItem.Type);
childResponse.IsExpanded.Should().BeFalse();
childResponse.ChildrenLoaded.Should().BeFalse();
if (childItem is Directory dir)
{
childResponse.Children.Should().NotBeNull();
childResponse.Children.Should().HaveCount(dir.Items.Count);
}
else
childResponse.Children.Should().BeEmpty();
}
}
result.Value.Any(r => r.Children.Count != 0).Should().BeTrue();
_mockDirectoryService.Received(1).GetSubdirectories(query.Path!, query.IncludeHiddenElements);
}
}
@@ -0,0 +1,113 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation.TestHelper;
using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetTreeDirectories;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Queries.GetTreeDirectories.Fixtures;
using Lumina.Domain.Common.Errors;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Queries.GetTreeDirectories;
/// <summary>
/// Contains unit tests for the <see cref="GetTreeDirectoriesQueryValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetTreeDirectoriesQueryValidatorTests
{
private readonly GetTreeDirectoriesQueryValidator _validator;
/// <summary>
/// Initializes a new instance of the <see cref="GetTreeDirectoriesQueryValidatorTests"/> class.
/// </summary>
public GetTreeDirectoriesQueryValidatorTests()
{
_validator = new GetTreeDirectoriesQueryValidator();
}
[Fact]
public void Validate_WhenPathIsNull_ShouldHaveValidationError()
{
// Arrange
GetTreeDirectoriesQuery query = GetTreeDirectoriesQueryFixture.CreateGetTreeDirectoryQuery();
query = query with { Path = null! };
// Act
TestValidationResult<GetTreeDirectoriesQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationErrorFor(x => x.Path)
.WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
}
[Fact]
public void Validate_WhenPathIsEmpty_ShouldHaveValidationError()
{
// Arrange
GetTreeDirectoriesQuery query = GetTreeDirectoriesQueryFixture.CreateGetTreeDirectoryQuery();
query = query with { Path = string.Empty };
// Act
TestValidationResult<GetTreeDirectoriesQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationErrorFor(x => x.Path)
.WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
}
[Fact]
public void Validate_WhenPathIsWhitespace_ShouldHaveValidationError()
{
// Arrange
GetTreeDirectoriesQuery query = GetTreeDirectoriesQueryFixture.CreateGetTreeDirectoryQuery();
query = query with { Path = " " };
// Act
TestValidationResult<GetTreeDirectoriesQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationErrorFor(x => x.Path)
.WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
}
[Fact]
public void Validate_WhenPathIsValid_ShouldNotHaveValidationError()
{
// Arrange
GetTreeDirectoriesQuery query = GetTreeDirectoriesQueryFixture.CreateGetTreeDirectoryQuery();
query = query with { Path = "/valid/path" };
// Act
TestValidationResult<GetTreeDirectoriesQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationErrorFor(x => x.Path);
}
[Fact]
public void Validate_WhenIncludeHiddenElementsIsTrue_ShouldNotHaveValidationError()
{
// Arrange
GetTreeDirectoriesQuery query = GetTreeDirectoriesQueryFixture.CreateGetTreeDirectoryQuery();
query = query with { IncludeHiddenElements = true };
// Act
TestValidationResult<GetTreeDirectoriesQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationErrorFor(x => x.IncludeHiddenElements);
}
[Fact]
public void Validate_WhenIncludeHiddenElementsIsFalse_ShouldNotHaveValidationError()
{
// Arrange
GetTreeDirectoriesQuery query = GetTreeDirectoriesQueryFixture.CreateGetTreeDirectoryQuery();
query = query with { IncludeHiddenElements = false };
// Act
TestValidationResult<GetTreeDirectoriesQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationErrorFor(x => x.IncludeHiddenElements);
}
}
@@ -0,0 +1,58 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Contracts.Enums.FileSystem;
using Lumina.Contracts.Responses.FileSystemManagement.Common;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Drives.Queries.GetDrives.Fixtures;
/// <summary>
/// Fixture class for the <see cref="GetDrivesQueryFixture"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDrivesQueryFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a single <see cref="FileSystemTreeNodeResponse"/> with a nested structure.
/// </summary>
/// <param name="currentDepth">The current depth in the tree structure. Default is 0 (root level).</param>
/// <param name="maxDepth">The maximum depth of the tree structure. Default is 2.</param>
/// <param name="maxChildren">The maximum number of children for each node. Default is 3.</param>
/// <returns>A <see cref="FileSystemTreeNodeResponse"/> with a nested structure.</returns>
public FileSystemTreeNodeResponse Create(int currentDepth = 0, int maxDepth = 2, int maxChildren = 3)
{
FileSystemTreeNodeResponse response = new()
{
Path = _faker.System.FilePath(),
Name = _faker.System.FileName(),
ItemType = FileSystemItemType.Directory,
IsExpanded = _faker.Random.Bool(),
ChildrenLoaded = true,
Children = []
};
if (currentDepth < maxDepth)
{
int childCount = _faker.Random.Int(1, maxChildren);
for (int i = 0; i < childCount; i++)
response.Children.Add(Create(currentDepth + 1, maxDepth, maxChildren));
}
return response;
}
/// <summary>
/// Creates a list of <see cref="FileSystemTreeNodeResponse"/> objects, each with a nested structure.
/// </summary>
/// <param name="count">The number of root-level nodes to create. Default is 2.</param>
/// <param name="maxDepth">The maximum depth of the tree structure for each root node. Default is 2.</param>
/// <param name="maxChildren">The maximum number of children for each node. Default is 3.</param>
/// <returns>A list of <see cref="FileSystemTreeNodeResponse"/> objects with nested structures.</returns>
public List<FileSystemTreeNodeResponse> CreateMany(int count = 2, int maxDepth = 2, int maxChildren = 3)
{
return Enumerable.Range(0, count).Select(_ => Create(0, maxDepth, maxChildren)).ToList();
}
}
@@ -0,0 +1,119 @@
#region ========================================================================= USING =====================================================================================
using AutoFixture;
using AutoFixture.AutoNSubstitute;
using ErrorOr;
using FluentAssertions;
using Lumina.Application.Core.FileSystemManagement.Drives.Queries.GetDrives;
using Lumina.Contracts.Enums.FileSystem;
using Lumina.Contracts.Responses.FileSystemManagement.Common;
using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate;
using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities;
using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services;
using NSubstitute;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Drives.Queries.GetDrives;
/// <summary>
/// Contains unit tests for the <see cref="GetDrivesQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDrivesQueryHandlerTests
{
private readonly IFixture _fixture;
private readonly IDriveService _mockDriveService;
private readonly GetDrivesQueryHandler _sut;
/// <summary>
/// Initializes a new instance of the <see cref="GetDrivesQueryHandlerTests"/> class.
/// </summary>
public GetDrivesQueryHandlerTests()
{
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
_mockDriveService = Substitute.For<IDriveService>();
_sut = new GetDrivesQueryHandler(_mockDriveService);
}
[Fact]
public async Task Handle_WhenCalled_ShouldReturnSuccessResult()
{
// Arrange
GetDrivesQuery getDrivesQuery = _fixture.Create<GetDrivesQuery>();
IEnumerable<FileSystemItem> drives =
[
WindowsRootItem.Create("C:\\", "C:").Value,
WindowsRootItem.Create("D:\\", "D:").Value
];
_mockDriveService.GetDrives()
.Returns(ErrorOrFactory.From(drives));
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sut.Handle(getDrivesQuery, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeAssignableTo<IEnumerable<FileSystemTreeNodeResponse>>();
result.Value.Should().HaveCount(drives.Count());
List<FileSystemTreeNodeResponse> resultList = result.Value.ToList();
List<FileSystemItem> drivesList = drives.ToList();
for (int i = 0; i < resultList.Count; i++)
{
FileSystemTreeNodeResponse response = resultList[i];
WindowsRootItem drive = (WindowsRootItem)drivesList[i];
response.Path.Should().Be(drive.Id.Path);
response.Name.Should().Be(drive.Name);
response.ItemType.Should().Be(FileSystemItemType.Root);
response.IsExpanded.Should().BeFalse();
response.ChildrenLoaded.Should().BeFalse();
response.Children.Should().BeEmpty();
}
_mockDriveService.Received(1).GetDrives();
}
[Fact]
public async Task Handle_WhenDriveServiceReturnsError_ShouldReturnFailureResult()
{
// Arrange
GetDrivesQuery query = _fixture.Create<GetDrivesQuery>();
Error error = Error.Failure("DriveService.Error", "An error occurred");
_mockDriveService.GetDrives()
.Returns(error);
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(error);
_mockDriveService.Received(1).GetDrives();
}
[Fact]
public async Task Handle_WhenDriveServiceReturnsEmptyList_ShouldReturnEmptySuccessResult()
{
// Arrange
GetDrivesQuery query = _fixture.Create<GetDrivesQuery>();
ErrorOr<IEnumerable<FileSystemItem>> emptyList = ErrorOrFactory.From(Enumerable.Empty<FileSystemItem>());
_mockDriveService.GetDrives()
.Returns(emptyList);
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeEmpty();
_mockDriveService.Received(1).GetDrives();
}
}
@@ -0,0 +1,33 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using ErrorOr;
using Lumina.Contracts.Enums.FileSystem;
using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.FileSystem.Fixtures;
/// <summary>
/// Fixture class for the <see cref="UnixRootItem"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UnixRootItemFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="UnixRootItem"/>.
/// </summary>
/// <returns>The created <see cref="UnixRootItem"/>.</returns>
public UnixRootItem Create()
{
ErrorOr<UnixRootItem> unixRootItemResult = UnixRootItem.Create(
_faker.PickRandom<FileSystemItemStatus>()
);
if (unixRootItemResult.IsError)
throw new InvalidOperationException("Failed to create File: " + string.Join(", ", unixRootItemResult.Errors));
return unixRootItemResult.Value;
}
}
@@ -0,0 +1,35 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using ErrorOr;
using Lumina.Contracts.Enums.FileSystem;
using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.FileSystem.Fixtures;
/// <summary>
/// Fixture class for the <see cref="WindowsRootItem"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class WindowsRootItemFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="WindowsRootItem"/>.
/// </summary>
/// <returns>The created <see cref="WindowsRootItem"/>.</returns>
public WindowsRootItem Create()
{
ErrorOr<WindowsRootItem> windowsRootItemResult = WindowsRootItem.Create(
_faker.System.FilePath(),
_faker.System.FileName(),
_faker.PickRandom<FileSystemItemStatus>()
);
if (windowsRootItemResult.IsError)
throw new InvalidOperationException("Failed to create File: " + string.Join(", ", windowsRootItemResult.Errors));
return windowsRootItemResult.Value;
}
}
@@ -0,0 +1,108 @@
#region ========================================================================= USING =====================================================================================
using AutoFixture;
using AutoFixture.AutoNSubstitute;
using FluentAssertions;
using Lumina.Application.Core.FileSystemManagement.FileSystem.Queries.GetFileSystem;
using Lumina.Contracts.Enums.FileSystem;
using Lumina.Contracts.Responses.FileSystemManagement.FileSystem;
using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Strategies.Platform;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.FileSystem.Queries.GetFileSystem;
/// <summary>
/// Contains unit tests for the <see cref="GetFileSystemQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetFileSystemQueryHandlerTests
{
private readonly IFixture _fixture;
private readonly IPlatformContextManager _mockPlatformContextManager;
private readonly IPlatformContext _mockPlatformContext;
private readonly GetFileSystemQueryHandler _sut;
/// <summary>
/// Initializes a new instance of the <see cref="GetFileSystemQueryHandlerTests"/> class.
/// </summary>
public GetFileSystemQueryHandlerTests()
{
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
_mockPlatformContextManager = Substitute.For<IPlatformContextManager>();
_mockPlatformContext = Substitute.For<IPlatformContext>();
_mockPlatformContextManager.GetCurrentContext().Returns(_mockPlatformContext);
_sut = new GetFileSystemQueryHandler(_mockPlatformContextManager);
}
[Theory]
[InlineData(PlatformType.Unix)]
[InlineData(PlatformType.Windows)]
public async Task Handle_WhenCalled_ShouldReturnCorrectFileSystemTypeResponse(PlatformType platformType)
{
// Arrange
GetFileSystemQuery query = _fixture.Create<GetFileSystemQuery>();
_mockPlatformContext.Platform.Returns(platformType);
// Act
FileSystemTypeResponse result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.Should().NotBeNull();
result.PlatformType.Should().Be(platformType);
_mockPlatformContextManager.Received(1).GetCurrentContext();
}
[Fact]
public async Task Handle_WhenCalled_ShouldReturnValueTaskResult()
{
// Arrange
GetFileSystemQuery query = _fixture.Create<GetFileSystemQuery>();
_mockPlatformContext.Platform.Returns(PlatformType.Unix);
// Act
ValueTask<FileSystemTypeResponse> resultTask = _sut.Handle(query, CancellationToken.None);
// Assert
resultTask.IsCompleted.Should().BeTrue();
FileSystemTypeResponse result = await resultTask;
result.Should().NotBeNull();
result.PlatformType.Should().Be(PlatformType.Unix);
}
[Fact]
public async Task Handle_WhenCalled_ShouldNotDependOnQueryContent()
{
// Arrange
GetFileSystemQuery query1 = _fixture.Create<GetFileSystemQuery>();
GetFileSystemQuery query2 = _fixture.Create<GetFileSystemQuery>();
_mockPlatformContext.Platform.Returns(PlatformType.Windows);
// Act
FileSystemTypeResponse result1 = await _sut.Handle(query1, CancellationToken.None);
FileSystemTypeResponse result2 = await _sut.Handle(query2, CancellationToken.None);
// Assert
result1.Should().BeEquivalentTo(result2);
_mockPlatformContextManager.Received(1).GetCurrentContext();
}
[Fact]
public async Task Handle_WhenCalled_ShouldIgnoreCancellationToken()
{
// Arrange
GetFileSystemQuery query = _fixture.Create<GetFileSystemQuery>();
_mockPlatformContext.Platform.Returns(PlatformType.Unix);
CancellationToken cancellationToken = new(true);
// Act
Func<Task> act = async () => await _sut.Handle(query, cancellationToken);
// Assert
await act.Should().NotThrowAsync();
_mockPlatformContextManager.Received(1).GetCurrentContext();
}
}
@@ -0,0 +1,82 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using ErrorOr;
using Lumina.Contracts.Enums.FileSystem;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Fixtures;
/// <summary>
/// Fixture class for the <see cref="File"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class FileFixture
{
private readonly Faker _faker;
/// <summary>
/// Initializes a new instance of the <see cref="FileFixture"/> class.
/// </summary>
public FileFixture()
{
_faker = new Faker();
}
/// <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;
}
}
@@ -0,0 +1,43 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Contracts.Responses.FileSystemManagement.Files;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Fixtures;
/// <summary>
/// Fixture class for the <see cref="FileResponse"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class FileResponseFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="FileResponse"/>.
/// </summary>
/// <returns>The created <see cref="FileResponse"/>.</returns>
public FileResponse Create()
{
return new FileResponse(
_faker.System.FilePath(),
_faker.System.FileName(),
_faker.Date.Past(),
_faker.Date.Recent(),
_faker.Random.Long()
);
}
/// <summary>
/// Creates a list of <see cref="FileResponse"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<FileResponse> CreateMany(int count = 3)
{
return Enumerable.Range(0, count).Select(_ => Create()).ToList();
}
}
@@ -0,0 +1,30 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Core.FileSystemManagement.Files.Queries.GetFiles;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Queries.GetFiles.Fixtures;
/// <summary>
/// Fixture class for the <see cref="GetFilesQuery"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetFilesQueryFixture
{
/// <summary>
/// Creates a random valid query to get files.
/// </summary>
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
/// <returns>The created query to get files.</returns>
public static GetFilesQuery CreateGetFilesQuery(bool includeHiddenElements = false)
{
return new Faker<GetFilesQuery>()
.CustomInstantiator(f => new GetFilesQuery(
default!,
default
))
.RuleFor(x => x.Path, f => f.System.FilePath())
.RuleFor(x => x.IncludeHiddenElements, f => includeHiddenElements);
}
}
@@ -0,0 +1,149 @@
#region ========================================================================= USING =====================================================================================
using AutoFixture;
using AutoFixture.AutoNSubstitute;
using ErrorOr;
using FluentAssertions;
using Lumina.Application.Core.FileSystemManagement.Files.Queries.GetFiles;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Fixtures;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Queries.GetFiles.Fixtures;
using Lumina.Contracts.Responses.FileSystemManagement.Files;
using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities;
using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Queries.GetFiles;
/// <summary>
/// Contains unit tests for the <see cref="GetFilesQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetFilesQueryHandlerTests
{
private readonly IFixture _fixture;
private readonly IFileService _mockFileService;
private readonly GetFilesQueryHandler _sut;
private readonly FileFixture _fileFixture;
/// <summary>
/// Initializes a new instance of the <see cref="GetFilesQueryHandlerTests"/> class.
/// </summary>
public GetFilesQueryHandlerTests()
{
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
_mockFileService = Substitute.For<IFileService>();
_sut = new GetFilesQueryHandler(_mockFileService);
_fileFixture = new FileFixture();
}
[Fact]
public async Task Handle_WhenCalledWithValidQueryWithoutHiddenFiles_ShouldReturnSuccessResult()
{
// Arrange
GetFilesQuery getFilesQuery = GetFilesQueryFixture.CreateGetFilesQuery(false);
IEnumerable<File> files = _fileFixture.CreateMany();
_mockFileService.GetFiles(getFilesQuery.Path!, getFilesQuery.IncludeHiddenElements)
.Returns(ErrorOrFactory.From(files));
// Act
ErrorOr<IEnumerable<FileResponse>> result = await _sut.Handle(getFilesQuery, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeAssignableTo<IEnumerable<FileResponse>>();
result.Value.Should().HaveCount(files.Count());
List<FileResponse> resultList = result.Value.ToList();
List<File> filesList = files.ToList();
for (int i = 0; i < resultList.Count; i++)
{
resultList[i].Path.Should().Be(filesList[i].Id.Path);
resultList[i].Name.Should().Be(filesList[i].Name);
resultList[i].DateCreated.Should().Be(filesList[i].DateCreated.Value);
resultList[i].DateModified.Should().Be(filesList[i].DateModified.Value);
resultList[i].Size.Should().Be(filesList[i].Size);
}
_mockFileService.Received(1).GetFiles(getFilesQuery.Path!, getFilesQuery.IncludeHiddenElements);
}
[Fact]
public async Task Handle_WhenCalledWithValidQueryWithHiddenFiles_ShouldReturnSuccessResult()
{
// Arrange
GetFilesQuery getFilesQuery = GetFilesQueryFixture.CreateGetFilesQuery(true);
IEnumerable<File> files = _fileFixture.CreateMany();
_mockFileService.GetFiles(getFilesQuery.Path!, getFilesQuery.IncludeHiddenElements)
.Returns(ErrorOrFactory.From(files));
// Act
ErrorOr<IEnumerable<FileResponse>> result = await _sut.Handle(getFilesQuery, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeAssignableTo<IEnumerable<FileResponse>>();
result.Value.Should().HaveCount(files.Count());
List<FileResponse> resultList = result.Value.ToList();
List<File> filesList = files.ToList();
for (int i = 0; i < resultList.Count; i++)
{
resultList[i].Path.Should().Be(filesList[i].Id.Path);
resultList[i].Name.Should().Be(filesList[i].Name);
resultList[i].DateCreated.Should().Be(filesList[i].DateCreated.Value);
resultList[i].DateModified.Should().Be(filesList[i].DateModified.Value);
resultList[i].Size.Should().Be(filesList[i].Size);
}
_mockFileService.Received(1).GetFiles(getFilesQuery.Path!, getFilesQuery.IncludeHiddenElements);
}
[Fact]
public async Task Handle_WhenFileServiceReturnsError_ShouldReturnFailureResult()
{
// Arrange
GetFilesQuery query = _fixture.Create<GetFilesQuery>();
Error error = Error.Failure("FileService.Error", "An error occurred");
_mockFileService.GetFiles(query.Path!, query.IncludeHiddenElements)
.Returns(error);
// Act
ErrorOr<IEnumerable<FileResponse>> result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(error);
_mockFileService.Received(1).GetFiles(query.Path!, query.IncludeHiddenElements);
}
[Fact]
public async Task Handle_WhenFileServiceReturnsEmptyList_ShouldReturnEmptySuccessResult()
{
// Arrange
GetFilesQuery query = _fixture.Create<GetFilesQuery>();
ErrorOr<IEnumerable<File>> emptyList = ErrorOrFactory.From(Enumerable.Empty<File>());
_mockFileService.GetFiles(query.Path!, query.IncludeHiddenElements)
.Returns(emptyList);
// Act
ErrorOr<IEnumerable<FileResponse>> result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeEmpty();
_mockFileService.Received(1).GetFiles(query.Path!, query.IncludeHiddenElements);
}
}
@@ -0,0 +1,113 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation.TestHelper;
using Lumina.Application.Core.FileSystemManagement.Files.Queries.GetFiles;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Queries.GetFiles.Fixtures;
using Lumina.Domain.Common.Errors;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Queries.GetFiles;
/// <summary>
/// Contains unit tests for the <see cref="GetFilesQueryValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetFilesQueryValidatorTests
{
private readonly GetFilesQueryValidator _validator;
/// <summary>
/// Initializes a new instance of the <see cref="GetFilesQueryValidatorTests"/> class.
/// </summary>
public GetFilesQueryValidatorTests()
{
_validator = new GetFilesQueryValidator();
}
[Fact]
public void Validate_WhenPathIsNull_ShouldHaveValidationError()
{
// Arrange
GetFilesQuery query = GetFilesQueryFixture.CreateGetFilesQuery();
query = query with { Path = null! };
// Act
TestValidationResult<GetFilesQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationErrorFor(x => x.Path)
.WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
}
[Fact]
public void Validate_WhenPathIsEmpty_ShouldHaveValidationError()
{
// Arrange
GetFilesQuery query = GetFilesQueryFixture.CreateGetFilesQuery();
query = query with { Path = string.Empty };
// Act
TestValidationResult<GetFilesQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationErrorFor(x => x.Path)
.WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
}
[Fact]
public void Validate_WhenPathIsWhitespace_ShouldHaveValidationError()
{
// Arrange
GetFilesQuery query = GetFilesQueryFixture.CreateGetFilesQuery();
query = query with { Path = " " };
// Act
TestValidationResult<GetFilesQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationErrorFor(x => x.Path)
.WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
}
[Fact]
public void Validate_WhenPathIsValid_ShouldNotHaveValidationError()
{
// Arrange
GetFilesQuery query = GetFilesQueryFixture.CreateGetFilesQuery();
query = query with { Path = "/valid/path" };
// Act
TestValidationResult<GetFilesQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationErrorFor(x => x.Path);
}
[Fact]
public void Validate_WhenIncludeHiddenElementsIsTrue_ShouldNotHaveValidationError()
{
// Arrange
GetFilesQuery query = GetFilesQueryFixture.CreateGetFilesQuery();
query = query with { IncludeHiddenElements = true };
// Act
TestValidationResult<GetFilesQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationErrorFor(x => x.IncludeHiddenElements);
}
[Fact]
public void Validate_WhenIncludeHiddenElementsIsFalse_ShouldNotHaveValidationError()
{
// Arrange
GetFilesQuery query = GetFilesQueryFixture.CreateGetFilesQuery();
query = query with { IncludeHiddenElements = false };
// Act
TestValidationResult<GetFilesQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationErrorFor(x => x.IncludeHiddenElements);
}
}
@@ -0,0 +1,30 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Core.FileSystemManagement.Files.Queries.GetTreeFiles;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Queries.GetTreeFiles.Fixtures;
/// <summary>
/// Fixture class for the <see cref="GetTreeFilesQuery"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetTreeFilesQueryFixture
{
/// <summary>
/// Creates a random valid query to get files.
/// </summary>
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
/// <returns>The created query to get files.</returns>
public static GetTreeFilesQuery CreateGetFilesQuery(bool includeHiddenElements = false)
{
return new Faker<GetTreeFilesQuery>()
.CustomInstantiator(f => new GetTreeFilesQuery(
default!,
default
))
.RuleFor(x => x.Path, f => f.System.FilePath())
.RuleFor(x => x.IncludeHiddenElements, f => includeHiddenElements);
}
}
@@ -0,0 +1,150 @@
#region ========================================================================= USING =====================================================================================
using AutoFixture;
using AutoFixture.AutoNSubstitute;
using ErrorOr;
using FluentAssertions;
using Lumina.Application.Core.FileSystemManagement.Files.Queries.GetTreeFiles;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Fixtures;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Queries.GetTreeFiles.Fixtures;
using Lumina.Contracts.Enums.FileSystem;
using Lumina.Contracts.Responses.FileSystemManagement.Common;
using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Entities;
using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services;
using NSubstitute;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Queries.GetTreeFiles;
/// <summary>
/// Contains unit tests for the <see cref="GetTreeFilesQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetTreeFilesQueryHandlerTests
{
private readonly IFixture _fixture;
private readonly IFileService _mockFileService;
private readonly GetTreeFilesQueryHandler _sut;
private readonly FileFixture _fileFixture;
/// <summary>
/// Initializes a new instance of the <see cref="GetTreeFilesQueryHandler"/> class.
/// </summary>
public GetTreeFilesQueryHandlerTests()
{
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
_mockFileService = Substitute.For<IFileService>();
_sut = new GetTreeFilesQueryHandler(_mockFileService);
_fileFixture = new FileFixture();
}
[Fact]
public async Task Handle_WhenCalledWithValidQueryWithoutHiddenFiles_ShouldReturnSuccessResult()
{
// Arrange
GetTreeFilesQuery getFilesQuery = GetTreeFilesQueryFixture.CreateGetFilesQuery(false);
IEnumerable<File> files = _fileFixture.CreateMany();
_mockFileService.GetFiles(getFilesQuery.Path!, getFilesQuery.IncludeHiddenElements)
.Returns(ErrorOrFactory.From(files));
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sut.Handle(getFilesQuery, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeAssignableTo<IEnumerable<FileSystemTreeNodeResponse>>();
result.Value.Should().HaveCount(files.Count());
List<FileSystemTreeNodeResponse> resultList = result.Value.ToList();
List<File> filesList = files.ToList();
for (int i = 0; i < resultList.Count; i++)
{
resultList[i].Path.Should().Be(filesList[i].Id.Path);
resultList[i].Name.Should().Be(filesList[i].Name);
resultList[i].ItemType.Should().Be(FileSystemItemType.File);
resultList[i].IsExpanded.Should().BeFalse();
resultList[i].ChildrenLoaded.Should().BeFalse();
resultList[i].Children.Should().BeEmpty();
}
_mockFileService.Received(1).GetFiles(getFilesQuery.Path!, getFilesQuery.IncludeHiddenElements);
}
[Fact]
public async Task Handle_WhenCalledWithValidQueryWithHiddenFiles_ShouldReturnSuccessResult()
{
// Arrange
GetTreeFilesQuery getFilesQuery = GetTreeFilesQueryFixture.CreateGetFilesQuery(true);
IEnumerable<File> files = _fileFixture.CreateMany();
_mockFileService.GetFiles(getFilesQuery.Path!, getFilesQuery.IncludeHiddenElements)
.Returns(ErrorOrFactory.From(files));
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sut.Handle(getFilesQuery, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeAssignableTo<IEnumerable<FileSystemTreeNodeResponse>>();
result.Value.Should().HaveCount(files.Count());
List<FileSystemTreeNodeResponse> resultList = result.Value.ToList();
List<File> filesList = files.ToList();
for (int i = 0; i < resultList.Count; i++)
{
resultList[i].Path.Should().Be(filesList[i].Id.Path);
resultList[i].Name.Should().Be(filesList[i].Name);
resultList[i].ItemType.Should().Be(FileSystemItemType.File);
resultList[i].IsExpanded.Should().BeFalse();
resultList[i].ChildrenLoaded.Should().BeFalse();
resultList[i].Children.Should().BeEmpty();
}
_mockFileService.Received(1).GetFiles(getFilesQuery.Path!, getFilesQuery.IncludeHiddenElements);
}
[Fact]
public async Task Handle_WhenFileServiceReturnsError_ShouldReturnFailureResult()
{
// Arrange
GetTreeFilesQuery query = _fixture.Create<GetTreeFilesQuery>();
Error error = Error.Failure("FileService.Error", "An error occurred");
_mockFileService.GetFiles(query.Path!, query.IncludeHiddenElements)
.Returns(error);
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(error);
_mockFileService.Received(1).GetFiles(query.Path!, query.IncludeHiddenElements);
}
[Fact]
public async Task Handle_WhenFileServiceReturnsEmptyList_ShouldReturnEmptySuccessResult()
{
// Arrange
GetTreeFilesQuery query = _fixture.Create<GetTreeFilesQuery>();
ErrorOr<IEnumerable<File>> emptyList = ErrorOrFactory.From(Enumerable.Empty<File>());
_mockFileService.GetFiles(query.Path!, query.IncludeHiddenElements)
.Returns(emptyList);
// Act
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeEmpty();
_mockFileService.Received(1).GetFiles(query.Path!, query.IncludeHiddenElements);
}
}
@@ -0,0 +1,113 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation.TestHelper;
using Lumina.Application.Core.FileSystemManagement.Files.Queries.GetTreeFiles;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Queries.GetTreeFiles.Fixtures;
using Lumina.Domain.Common.Errors;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Queries.GetTreeFiles;
/// <summary>
/// Contains unit tests for the <see cref="GetTreeFilesQueryValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetTreeFilesQueryValidatorTests
{
private readonly GetTreeFilesQueryValidator _validator;
/// <summary>
/// Initializes a new instance of the <see cref="GetTreeFilesQueryValidatorTests"/> class.
/// </summary>
public GetTreeFilesQueryValidatorTests()
{
_validator = new GetTreeFilesQueryValidator();
}
[Fact]
public void Validate_WhenPathIsNull_ShouldHaveValidationError()
{
// Arrange
GetTreeFilesQuery query = GetTreeFilesQueryFixture.CreateGetFilesQuery();
query = query with { Path = null! };
// Act
TestValidationResult<GetTreeFilesQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationErrorFor(x => x.Path)
.WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
}
[Fact]
public void Validate_WhenPathIsEmpty_ShouldHaveValidationError()
{
// Arrange
GetTreeFilesQuery query = GetTreeFilesQueryFixture.CreateGetFilesQuery();
query = query with { Path = string.Empty };
// Act
TestValidationResult<GetTreeFilesQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationErrorFor(x => x.Path)
.WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
}
[Fact]
public void Validate_WhenPathIsWhitespace_ShouldHaveValidationError()
{
// Arrange
GetTreeFilesQuery query = GetTreeFilesQueryFixture.CreateGetFilesQuery();
query = query with { Path = " " };
// Act
TestValidationResult<GetTreeFilesQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationErrorFor(x => x.Path)
.WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
}
[Fact]
public void Validate_WhenPathIsValid_ShouldNotHaveValidationError()
{
// Arrange
GetTreeFilesQuery query = GetTreeFilesQueryFixture.CreateGetFilesQuery();
query = query with { Path = "/valid/path" };
// Act
TestValidationResult<GetTreeFilesQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationErrorFor(x => x.Path);
}
[Fact]
public void Validate_WhenIncludeHiddenElementsIsTrue_ShouldNotHaveValidationError()
{
// Arrange
GetTreeFilesQuery query = GetTreeFilesQueryFixture.CreateGetFilesQuery();
query = query with { IncludeHiddenElements = true };
// Act
TestValidationResult<GetTreeFilesQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationErrorFor(x => x.IncludeHiddenElements);
}
[Fact]
public void Validate_WhenIncludeHiddenElementsIsFalse_ShouldNotHaveValidationError()
{
// Arrange
GetTreeFilesQuery query = GetTreeFilesQueryFixture.CreateGetFilesQuery();
query = query with { IncludeHiddenElements = false };
// Act
TestValidationResult<GetTreeFilesQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationErrorFor(x => x.IncludeHiddenElements);
}
}
@@ -0,0 +1,42 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using ErrorOr;
using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Fixtures;
/// <summary>
/// Fixture class for the <see cref="FileSystemPathId"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class FileSystemPathIdFixture
{
private readonly Faker _faker;
/// <summary>
/// Initializes a new instance of the <see cref="FileSystemPathIdFixture"/> class.
/// </summary>
public FileSystemPathIdFixture()
{
_faker = new Faker();
}
/// <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;
}
}
@@ -0,0 +1,93 @@
#region ========================================================================= USING =====================================================================================
using AutoFixture;
using AutoFixture.AutoNSubstitute;
using ErrorOr;
using FluentAssertions;
using Lumina.Application.Core.FileSystemManagement.Paths.Commands.CombinePath;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Commands.CombinePath.Fixtures;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services;
using NSubstitute;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Commands.CombinePath;
/// <summary>
/// Contains unit tests for the <see cref="CombinePathCommandHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class CombinePathCommandHandlerTests
{
private readonly IFixture _fixture;
private readonly IPathService _mockPathService;
private readonly CombinePathCommandHandler _sut;
/// <summary>
/// Initializes a new instance of the <see cref="CombinePathCommandHandlerTests"/> class.
/// </summary>
public CombinePathCommandHandlerTests()
{
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
_mockPathService = Substitute.For<IPathService>();
_sut = new CombinePathCommandHandler(_mockPathService);
}
[Fact]
public async Task Handle_WhenCalledWithValidCommand_ShouldReturnSuccessResult()
{
// Arrange
CombinePathCommand combinePathCommand = CombinePathCommandFixture.CreateCombinePathCommand();
string combinedPath = System.IO.Path.Combine(combinePathCommand.OriginalPath!, combinePathCommand.NewPath!);
_mockPathService.CombinePath(combinePathCommand.OriginalPath!, combinePathCommand.NewPath!)
.Returns(ErrorOrFactory.From(combinedPath));
// Act
ErrorOr<PathSegmentResponse> result = await _sut.Handle(combinePathCommand, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeOfType<PathSegmentResponse>();
result.Value.Path.Should().Be(combinedPath);
_mockPathService.Received(1).CombinePath(combinePathCommand.OriginalPath!, combinePathCommand.NewPath!);
}
[Fact]
public async Task Handle_WhenPathServiceReturnsError_ShouldReturnFailureResult()
{
// Arrange
CombinePathCommand command = _fixture.Create<CombinePathCommand>();
Error error = Error.Failure("PathService.Error", "An error occurred");
_mockPathService.CombinePath(command.OriginalPath!, command.NewPath!)
.Returns(error);
// Act
ErrorOr<PathSegmentResponse> result = await _sut.Handle(command, CancellationToken.None);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(error);
_mockPathService.Received(1).CombinePath(command.OriginalPath!, command.NewPath!);
}
[Fact]
public async Task Handle_WhenPathServiceReturnsEmptyString_ShouldReturnSuccessResultWithEmptyPath()
{
// Arrange
CombinePathCommand command = _fixture.Create<CombinePathCommand>();
_mockPathService.CombinePath(command.OriginalPath!, command.NewPath!)
.Returns(ErrorOrFactory.From(string.Empty));
// Act
ErrorOr<PathSegmentResponse> result = await _sut.Handle(command, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeOfType<PathSegmentResponse>();
result.Value.Path.Should().BeEmpty();
_mockPathService.Received(1).CombinePath(command.OriginalPath!, command.NewPath!);
}
}
@@ -0,0 +1,131 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation.TestHelper;
using Lumina.Application.Core.FileSystemManagement.Paths.Commands.CombinePath;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Commands.CombinePath.Fixtures;
using Lumina.Domain.Common.Errors;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Commands.CombinePath;
/// <summary>
/// Contains unit tests for the <see cref="CombinePathCommandValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class CombinePathCommandValidatorTests
{
private readonly CombinePathCommandValidator _validator;
/// <summary>
/// Initializes a new instance of the <see cref="CombinePathCommandValidatorTests"/> class.
/// </summary>
public CombinePathCommandValidatorTests()
{
_validator = new CombinePathCommandValidator();
}
[Fact]
public void Validate_WhenOriginalPathIsNull_ShouldHaveValidationError()
{
// Arrange
CombinePathCommand command = CombinePathCommandFixture.CreateCombinePathCommand();
command = command with { OriginalPath = null! };
// Act
TestValidationResult<CombinePathCommand> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationErrorFor(x => x.OriginalPath)
.WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
}
[Fact]
public void Validate_WhenOriginalPathIsEmpty_ShouldHaveValidationError()
{
// Arrange
CombinePathCommand command = CombinePathCommandFixture.CreateCombinePathCommand();
command = command with { OriginalPath = string.Empty };
// Act
TestValidationResult<CombinePathCommand> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationErrorFor(x => x.OriginalPath)
.WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
}
[Fact]
public void Validate_WhenOriginalPathIsWhitespace_ShouldHaveValidationError()
{
// Arrange
CombinePathCommand command = CombinePathCommandFixture.CreateCombinePathCommand();
command = command with { OriginalPath = " " };
// Act
TestValidationResult<CombinePathCommand> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationErrorFor(x => x.OriginalPath)
.WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
}
[Fact]
public void Validate_WhenNewPathIsNull_ShouldHaveValidationError()
{
// Arrange
CombinePathCommand command = CombinePathCommandFixture.CreateCombinePathCommand();
command = command with { NewPath = null! };
// Act
TestValidationResult<CombinePathCommand> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationErrorFor(x => x.NewPath)
.WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
}
[Fact]
public void Validate_WhenNewPathIsEmpty_ShouldHaveValidationError()
{
// Arrange
CombinePathCommand command = CombinePathCommandFixture.CreateCombinePathCommand();
command = command with { NewPath = string.Empty };
// Act
TestValidationResult<CombinePathCommand> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationErrorFor(x => x.NewPath)
.WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
}
[Fact]
public void Validate_WhenNewPathIsWhitespace_ShouldHaveValidationError()
{
// Arrange
CombinePathCommand command = CombinePathCommandFixture.CreateCombinePathCommand();
command = command with { NewPath = " " };
// Act
TestValidationResult<CombinePathCommand> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationErrorFor(x => x.NewPath)
.WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
}
[Fact]
public void Validate_WhenBothPathsAreValid_ShouldNotHaveValidationError()
{
// Arrange
CombinePathCommand command = CombinePathCommandFixture.CreateCombinePathCommand();
command = command with { OriginalPath = "/valid/path", NewPath = "new/segment" };
// Act
TestValidationResult<CombinePathCommand> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationErrorFor(x => x.OriginalPath);
result.ShouldNotHaveValidationErrorFor(x => x.NewPath);
}
}
@@ -0,0 +1,29 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Core.FileSystemManagement.Paths.Commands.CombinePath;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Commands.CombinePath.Fixtures;
/// <summary>
/// Fixture class for the <see cref="CombinePathCommand"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class CombinePathCommandFixture
{
/// <summary>
/// Creates a random valid command to combine paths.
/// </summary>
/// <returns>The created command.</returns>
public static CombinePathCommand CreateCombinePathCommand()
{
return new Faker<CombinePathCommand>()
.CustomInstantiator(f => new CombinePathCommand(
default!,
default!
))
.RuleFor(x => x.OriginalPath, f => f.System.FilePath())
.RuleFor(x => x.NewPath, f => f.System.FilePath());
}
}
@@ -0,0 +1,27 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Core.FileSystemManagement.Paths.Commands.SplitPath;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Commands.SplitPath.Fixtures;
/// <summary>
/// Fixture class for the <see cref="SplitPathCommand"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SplitPathCommandFixture
{
/// <summary>
/// Creates a random valid command for splitting paths.
/// </summary>
/// <returns>The created command.</returns>
public static SplitPathCommand CreateSplitPathCommand()
{
return new Faker<SplitPathCommand>()
.CustomInstantiator(f => new SplitPathCommand(
default!
))
.RuleFor(x => x.Path, f => f.System.FilePath());
}
}
@@ -0,0 +1,107 @@
#region ========================================================================= USING =====================================================================================
using AutoFixture;
using AutoFixture.AutoNSubstitute;
using ErrorOr;
using FluentAssertions;
using Lumina.Application.Core.FileSystemManagement.Paths.Commands.SplitPath;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Commands.SplitPath.Fixtures;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Fixtures;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services;
using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Commands.SplitPath;
/// <summary>
/// Contains unit tests for the <see cref="SplitPathCommandHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SplitPathCommandHandlerTests
{
private readonly IFixture _fixture;
private readonly IPathService _mockPathService;
private readonly SplitPathCommandHandler _sut;
private readonly PathSegmentFixture _pathSegmentFixture;
/// <summary>
/// Initializes a new instance of the <see cref="SplitPathCommandHandlerTests"/> class.
/// </summary>
public SplitPathCommandHandlerTests()
{
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
_mockPathService = Substitute.For<IPathService>();
_sut = new SplitPathCommandHandler(_mockPathService);
_pathSegmentFixture = new PathSegmentFixture();
}
[Fact]
public async Task Handle_WhenCalledWithValidCommand_ShouldReturnSuccessResult()
{
// Arrange
SplitPathCommand splitPathCommand = SplitPathCommandFixture.CreateSplitPathCommand();
IEnumerable<PathSegment> pathSegments = _pathSegmentFixture.CreateMany();
_mockPathService.ParsePath(splitPathCommand.Path!)
.Returns(ErrorOrFactory.From(pathSegments));
// Act
ErrorOr<IEnumerable<PathSegmentResponse>> result = await _sut.Handle(splitPathCommand, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeAssignableTo<IEnumerable<PathSegmentResponse>>();
result.Value.Should().HaveCount(pathSegments.Count());
List<PathSegmentResponse> resultList = result.Value.ToList();
List<PathSegment> segmentsList = pathSegments.ToList();
for (int i = 0; i < resultList.Count; i++)
resultList[i].Path.Should().Be(segmentsList[i].Name);
_mockPathService.Received(1).ParsePath(splitPathCommand.Path!);
}
[Fact]
public async Task Handle_WhenPathServiceReturnsError_ShouldReturnFailureResult()
{
// Arrange
SplitPathCommand command = _fixture.Create<SplitPathCommand>();
Error error = Error.Failure("PathService.Error", "An error occurred");
_mockPathService.ParsePath(command.Path!)
.Returns(error);
// Act
ErrorOr<IEnumerable<PathSegmentResponse>> result = await _sut.Handle(command, CancellationToken.None);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(error);
_mockPathService.Received(1).ParsePath(command.Path!);
}
[Fact]
public async Task Handle_WhenPathServiceReturnsEmptyList_ShouldReturnEmptySuccessResult()
{
// Arrange
SplitPathCommand command = _fixture.Create<SplitPathCommand>();
ErrorOr<IEnumerable<PathSegment>> emptyList = ErrorOrFactory.From(Enumerable.Empty<PathSegment>());
_mockPathService.ParsePath(command.Path!)
.Returns(emptyList);
// Act
ErrorOr<IEnumerable<PathSegmentResponse>> result = await _sut.Handle(command, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeEmpty();
_mockPathService.Received(1).ParsePath(command.Path!);
}
}
@@ -0,0 +1,85 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation.TestHelper;
using Lumina.Application.Core.FileSystemManagement.Paths.Commands.SplitPath;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Commands.SplitPath.Fixtures;
using Lumina.Domain.Common.Errors;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Commands.SplitPath;
/// <summary>
/// Contains unit tests for the <see cref="SplitPathCommandValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SplitPathCommandValidatorTests
{
private readonly SplitPathCommandValidator _validator;
/// <summary>
/// Initializes a new instance of the <see cref="SplitPathCommandValidatorTests"/> class.
/// </summary>
public SplitPathCommandValidatorTests()
{
_validator = new SplitPathCommandValidator();
}
[Fact]
public void Validate_WhenPathIsNull_ShouldHaveValidationError()
{
// Arrange
SplitPathCommand command = SplitPathCommandFixture.CreateSplitPathCommand();
command = command with { Path = null! };
// Act
TestValidationResult<SplitPathCommand> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationErrorFor(x => x.Path)
.WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
}
[Fact]
public void Validate_WhenPathIsEmpty_ShouldHaveValidationError()
{
// Arrange
SplitPathCommand command = SplitPathCommandFixture.CreateSplitPathCommand();
command = command with { Path = string.Empty };
// Act
TestValidationResult<SplitPathCommand> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationErrorFor(x => x.Path)
.WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
}
[Fact]
public void Validate_WhenPathIsWhitespace_ShouldHaveValidationError()
{
// Arrange
SplitPathCommand command = SplitPathCommandFixture.CreateSplitPathCommand();
command = command with { Path = " " };
// Act
TestValidationResult<SplitPathCommand> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationErrorFor(x => x.Path)
.WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
}
[Fact]
public void Validate_WhenPathIsValid_ShouldNotHaveValidationError()
{
// Arrange
SplitPathCommand command = SplitPathCommandFixture.CreateSplitPathCommand();
command = command with { Path = "/valid/path" };
// Act
TestValidationResult<SplitPathCommand> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationErrorFor(x => x.Path);
}
}
@@ -0,0 +1,58 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using ErrorOr;
using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Fixtures;
/// <summary>
/// Fixture class for the <see cref="PathSegment"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class PathSegmentFixture
{
private readonly Faker _faker;
/// <summary>
/// Initializes a new instance of the <see cref="PathSegmentFixture"/> class.
/// </summary>
public PathSegmentFixture()
{
_faker = new Faker();
}
/// <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();
}
}
@@ -0,0 +1,37 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Fixtures;
/// <summary>
/// Fixture class for the <see cref="PathSegmentResponse"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class PathSegmentResponseFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="PathSegmentResponse"/>.
/// </summary>
/// <returns>The created <see cref="PathSegmentResponse"/>.</returns>
public PathSegmentResponse Create()
{
return new PathSegmentResponse(_faker.System.DirectoryPath());
}
/// <summary>
/// Creates a list of <see cref="PathSegmentResponse"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<PathSegmentResponse> CreateMany(int count = 3)
{
return Enumerable.Range(0, count).Select(_ => Create()).ToList();
}
}
@@ -0,0 +1,37 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Fixtures;
/// <summary>
/// Fixture class for the <see cref="PathSeparatorResponse"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class PathSeparatorResponseFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="PathSeparatorResponse"/>.
/// </summary>
/// <returns>The created <see cref="PathSeparatorResponse"/>.</returns>
public PathSeparatorResponse Create()
{
return new PathSeparatorResponse(_faker.System.DirectoryPath());
}
/// <summary>
/// Creates a list of <see cref="PathSeparatorResponse"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<PathSeparatorResponse> CreateMany(int count = 3)
{
return Enumerable.Range(0, count).Select(_ => Create()).ToList();
}
}
@@ -0,0 +1,123 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Application.Core.FileSystemManagement.Paths.Queries.CheckPathExists;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.CheckPathExists.Fixtures;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services;
using NSubstitute;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.CheckPathExists;
/// <summary>
/// Contains unit tests for the <see cref="CheckPathExistsQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class CheckPathExistsQueryHandlerTests
{
private readonly IPathService _mockPathService;
private readonly CheckPathExistsQueryHandler _sut;
/// <summary>
/// Initializes a new instance of the <see cref="CheckPathExistsQueryHandlerTests"/> class.
/// </summary>
public CheckPathExistsQueryHandlerTests()
{
_mockPathService = Substitute.For<IPathService>();
_sut = new CheckPathExistsQueryHandler(_mockPathService);
}
[Fact]
public async Task Handle_WhenPathExistsAndIsNotHidden_ShouldReturnTrueResponse()
{
// Arrange
CheckPathExistsQuery query = CheckPathExistsQueryFixture.CreateCheckPathExistsQuery();
_mockPathService.Exists(query.Path!).Returns(true);
// Act
PathExistsResponse result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.Exists.Should().BeTrue();
_mockPathService.Received(1).Exists(query.Path!);
}
[Fact]
public async Task Handle_WhenPathExistsAndIsHiddenAndIncludeHiddenElementsIsTrue_ShouldReturnTrueResponse()
{
// Arrange
CheckPathExistsQuery query = CheckPathExistsQueryFixture.CreateCheckPathExistsQuery(true);
_mockPathService.Exists(query.Path!).Returns(true);
// Act
PathExistsResponse result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.Exists.Should().BeTrue();
_mockPathService.Received(1).Exists(query.Path!);
}
[Fact]
public async Task Handle_WhenPathExistsAndIsHiddenAndIncludeHiddenElementsIsFalse_ShouldReturnFalseResponse()
{
// Arrange
CheckPathExistsQuery query = CheckPathExistsQueryFixture.CreateCheckPathExistsQuery(false);
_mockPathService.Exists(query.Path!, false).Returns(false);
// Act
PathExistsResponse result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.Exists.Should().BeFalse();
_mockPathService.Received(1).Exists(query.Path!, false);
}
[Fact]
public async Task Handle_WhenPathDoesNotExist_ShouldReturnFalseResponse()
{
// Arrange
CheckPathExistsQuery query = CheckPathExistsQueryFixture.CreateCheckPathExistsQuery();
_mockPathService.Exists(query.Path!).Returns(false);
// Act
PathExistsResponse result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.Exists.Should().BeFalse();
_mockPathService.Received(1).Exists(query.Path!);
}
[Fact]
public async Task Handle_WhenCalledWithNullPath_ShouldStillCallPathService()
{
// Arrange
CheckPathExistsQuery query = new(null!, false);
_mockPathService.Exists(Arg.Any<string>(), Arg.Any<bool>()).Returns(false);
// Act
PathExistsResponse result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.Exists.Should().BeFalse();
_mockPathService.Received(1).Exists(Arg.Any<string>(), Arg.Any<bool>());
}
[Fact]
public async Task Handle_WhenCancellationRequested_ShouldStillCompleteOperation()
{
// Arrange
CheckPathExistsQuery query = CheckPathExistsQueryFixture.CreateCheckPathExistsQuery();
_mockPathService.Exists(query.Path!).Returns(true);
CancellationToken cancellationToken = new(true);
// Act
PathExistsResponse result = await _sut.Handle(query, cancellationToken);
// Assert
result.Exists.Should().BeTrue();
_mockPathService.Received(1).Exists(query.Path!);
}
}
@@ -0,0 +1,85 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation.TestHelper;
using Lumina.Application.Core.FileSystemManagement.Paths.Queries.CheckPathExists;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.CheckPathExists.Fixtures;
using Lumina.Domain.Common.Errors;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.CheckPathExists;
/// <summary>
/// Contains unit tests for the <see cref="CheckPathExistsQueryValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class CheckPathExistsQueryValidatorTests
{
private readonly CheckPathExistsQueryValidator _validator;
/// <summary>
/// Initializes a new instance of the <see cref="CheckPathExistsQueryValidatorTests"/> class.
/// </summary>
public CheckPathExistsQueryValidatorTests()
{
_validator = new CheckPathExistsQueryValidator();
}
[Fact]
public void Validate_WhenPathIsNull_ShouldHaveValidationError()
{
// Arrange
CheckPathExistsQuery query = CheckPathExistsQueryFixture.CreateCheckPathExistsQuery();
query = query with { Path = null! };
// Act
TestValidationResult<CheckPathExistsQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationErrorFor(x => x.Path)
.WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
}
[Fact]
public void Validate_WhenPathIsEmpty_ShouldHaveValidationError()
{
// Arrange
CheckPathExistsQuery query = CheckPathExistsQueryFixture.CreateCheckPathExistsQuery();
query = query with { Path = string.Empty };
// Act
TestValidationResult<CheckPathExistsQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationErrorFor(x => x.Path)
.WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
}
[Fact]
public void Validate_WhenPathIsWhitespace_ShouldHaveValidationError()
{
// Arrange
CheckPathExistsQuery query = CheckPathExistsQueryFixture.CreateCheckPathExistsQuery();
query = query with { Path = " " };
// Act
TestValidationResult<CheckPathExistsQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationErrorFor(x => x.Path)
.WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
}
[Fact]
public void Validate_WhenPathIsValid_ShouldNotHaveValidationError()
{
// Arrange
CheckPathExistsQuery query = CheckPathExistsQueryFixture.CreateCheckPathExistsQuery();
query = query with { Path = "/valid/path" };
// Act
TestValidationResult<CheckPathExistsQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationErrorFor(x => x.Path);
}
}
@@ -0,0 +1,30 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Core.FileSystemManagement.Paths.Queries.CheckPathExists;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.CheckPathExists.Fixtures;
/// <summary>
/// Fixture class for the <see cref="CheckPathExistsQuery"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class CheckPathExistsQueryFixture
{
/// <summary>
/// Creates a random valid query to check if paths exist.
/// </summary>
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
/// <returns>The created query.</returns>
public static CheckPathExistsQuery CreateCheckPathExistsQuery(bool includeHiddenElements = true)
{
return new Faker<CheckPathExistsQuery>()
.CustomInstantiator(f => new CheckPathExistsQuery(
default!,
default
))
.RuleFor(x => x.Path, f => f.System.FilePath())
.RuleFor(x => x.IncludeHiddenElements, includeHiddenElements);
}
}
@@ -0,0 +1,27 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathParent;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.GetPathParent.Fixtures;
/// <summary>
/// Fixture class for the <see cref="GetPathParentQuery"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetPathParentQueryFixture
{
/// <summary>
/// Creates a random valid query to check if paths exist.
/// </summary>
/// <returns>The created query.</returns>
public static GetPathParentQuery CreateGetPathParentQuery()
{
return new Faker<GetPathParentQuery>()
.CustomInstantiator(f => new GetPathParentQuery(
default!
))
.RuleFor(x => x.Path, f => f.System.FilePath());
}
}
@@ -0,0 +1,100 @@
#region ========================================================================= USING =====================================================================================
using AutoFixture;
using AutoFixture.AutoNSubstitute;
using ErrorOr;
using FluentAssertions;
using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathParent;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Fixtures;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.GetPathParent.Fixtures;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services;
using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects;
using NSubstitute;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.GetPathParent;
/// <summary>
/// Contains unit tests for the <see cref="GetPathParentQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetPathParentQueryHandlerTests
{
private readonly IFixture _fixture;
private readonly IPathService _mockPathService;
private readonly GetPathParentQueryHandler _sut;
private readonly PathSegmentFixture _pathSegmentFixture;
public GetPathParentQueryHandlerTests()
{
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
_mockPathService = Substitute.For<IPathService>();
_sut = new GetPathParentQueryHandler(_mockPathService);
_pathSegmentFixture = new PathSegmentFixture();
}
[Fact]
public async Task Handle_WhenCalledWithValidQuery_ShouldReturnSuccessResult()
{
// Arrange
GetPathParentQuery query = GetPathParentQueryFixture.CreateGetPathParentQuery();
IEnumerable<PathSegment> pathSegments = _pathSegmentFixture.CreateMany();
// Create PathSegmentResponses based on the PathSegments
IEnumerable<PathSegmentResponse> pathSegmentResponses = pathSegments.Select(segment => new PathSegmentResponse(segment.Name));
_mockPathService.GoUpOneLevel(query.Path!)
.Returns(ErrorOrFactory.From(pathSegments));
// Act
ErrorOr<IEnumerable<PathSegmentResponse>> result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeAssignableTo<IEnumerable<PathSegmentResponse>>();
result.Value.Should().BeEquivalentTo(pathSegmentResponses);
_mockPathService.Received(1).GoUpOneLevel(query.Path!);
}
[Fact]
public async Task Handle_WhenPathServiceReturnsError_ShouldReturnFailureResult()
{
// Arrange
GetPathParentQuery query = _fixture.Create<GetPathParentQuery>();
Error error = Error.Failure("PathService.Error", "An error occurred");
_mockPathService.GoUpOneLevel(query.Path!)
.Returns(error);
// Act
ErrorOr<IEnumerable<PathSegmentResponse>> result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(error);
_mockPathService.Received(1).GoUpOneLevel(query.Path!);
}
[Fact]
public async Task Handle_WhenPathServiceReturnsEmptyList_ShouldReturnEmptySuccessResult()
{
// Arrange
GetPathParentQuery query = _fixture.Create<GetPathParentQuery>();
ErrorOr<IEnumerable<PathSegment>> emptyList = ErrorOrFactory.From(Enumerable.Empty<PathSegment>());
_mockPathService.GoUpOneLevel(query.Path!)
.Returns(emptyList);
// Act
ErrorOr<IEnumerable<PathSegmentResponse>> result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeEmpty();
_mockPathService.Received(1).GoUpOneLevel(query.Path!);
}
}
@@ -0,0 +1,85 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation.TestHelper;
using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathParent;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.GetPathParent.Fixtures;
using Lumina.Domain.Common.Errors;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.GetPathParent;
/// <summary>
/// Contains unit tests for the <see cref="GetPathParentQueryValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetPathParentQueryValidatorTests
{
private readonly GetPathParentQueryValidator _validator;
/// <summary>
/// Initializes a new instance of the <see cref="GetPathParentQueryValidatorTests"/> class.
/// </summary>
public GetPathParentQueryValidatorTests()
{
_validator = new GetPathParentQueryValidator();
}
[Fact]
public void Validate_WhenPathIsNull_ShouldHaveValidationError()
{
// Arrange
GetPathParentQuery query = GetPathParentQueryFixture.CreateGetPathParentQuery();
query = query with { Path = null! };
// Act
TestValidationResult<GetPathParentQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationErrorFor(x => x.Path)
.WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
}
[Fact]
public void Validate_WhenPathIsEmpty_ShouldHaveValidationError()
{
// Arrange
GetPathParentQuery query = GetPathParentQueryFixture.CreateGetPathParentQuery();
query = query with { Path = string.Empty };
// Act
TestValidationResult<GetPathParentQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationErrorFor(x => x.Path)
.WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
}
[Fact]
public void Validate_WhenPathIsWhitespace_ShouldHaveValidationError()
{
// Arrange
GetPathParentQuery query = GetPathParentQueryFixture.CreateGetPathParentQuery();
query = query with { Path = " " };
// Act
TestValidationResult<GetPathParentQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationErrorFor(x => x.Path)
.WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
}
[Fact]
public void Validate_WhenPathIsValid_ShouldNotHaveValidationError()
{
// Arrange
GetPathParentQuery query = GetPathParentQueryFixture.CreateGetPathParentQuery();
query = query with { Path = "/valid/path" };
// Act
TestValidationResult<GetPathParentQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationErrorFor(x => x.Path);
}
}
@@ -0,0 +1,27 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathRoot;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.GetPathRoot.Fixtures;
/// <summary>
/// Fixture class for the <see cref="GetPathRootQuery"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetPathRootQueryFixture
{
/// <summary>
/// Creates a random valid query to check if paths exist.
/// </summary>
/// <returns>The created query.</returns>
public static GetPathRootQuery CreateGetPathRootQuery()
{
return new Faker<GetPathRootQuery>()
.CustomInstantiator(f => new GetPathRootQuery(
default!
))
.RuleFor(x => x.Path, f => f.System.FilePath());
}
}
@@ -0,0 +1,95 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FluentAssertions;
using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathRoot;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Fixtures;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.GetPathRoot.Fixtures;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services;
using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects;
using NSubstitute;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.GetPathRoot;
/// <summary>
/// Contains unit tests for the <see cref="GetPathRootQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetPathRootQueryHandlerTests
{
private readonly IPathService _mockPathService;
private readonly GetPathRootQueryHandler _sut;
private readonly PathSegmentFixture _pathSegmentFixture;
/// <summary>
/// Initializes a new instance of the <see cref="GetPathRootQueryHandlerTests"/> class.
/// </summary>
public GetPathRootQueryHandlerTests()
{
_mockPathService = Substitute.For<IPathService>();
_sut = new GetPathRootQueryHandler(_mockPathService);
_pathSegmentFixture = new PathSegmentFixture();
}
[Fact]
public async Task Handle_WhenCalledWithValidQuery_ShouldReturnSuccessResult()
{
// Arrange
GetPathRootQuery query = GetPathRootQueryFixture.CreateGetPathRootQuery();
PathSegment pathSegment = _pathSegmentFixture.CreatePathSegment(isDrive: true);
_mockPathService.GetPathRoot(query.Path!)
.Returns(ErrorOrFactory.From(pathSegment));
// Act
ErrorOr<PathSegmentResponse> result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().NotBeNull();
result.Value.Path.Should().Be(pathSegment.Name);
_mockPathService.Received(1).GetPathRoot(query.Path!);
}
[Fact]
public async Task Handle_WhenPathServiceReturnsError_ShouldReturnFailureResult()
{
// Arrange
GetPathRootQuery query = GetPathRootQueryFixture.CreateGetPathRootQuery();
Error error = Error.Failure("PathService.Error", "An error occurred");
_mockPathService.GetPathRoot(query.Path!)
.Returns(error);
// Act
ErrorOr<PathSegmentResponse> result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(error);
_mockPathService.Received(1).GetPathRoot(query.Path!);
}
[Fact]
public async Task Handle_WhenPathServiceReturnsRootPathSegment_ShouldReturnRootSuccessResult()
{
// Arrange
GetPathRootQuery query = GetPathRootQueryFixture.CreateGetPathRootQuery();
PathSegment rootPathSegment = _pathSegmentFixture.CreatePathSegment(name: "/", isDirectory: true, isDrive: true);
_mockPathService.GetPathRoot(query.Path!)
.Returns(ErrorOrFactory.From(rootPathSegment));
// Act
ErrorOr<PathSegmentResponse> result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().NotBeNull();
result.Value.Path.Should().Be("/");
_mockPathService.Received(1).GetPathRoot(query.Path!);
}
}
@@ -0,0 +1,85 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation.TestHelper;
using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathRoot;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.GetPathRoot.Fixtures;
using Lumina.Domain.Common.Errors;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.GetPathRoot;
/// <summary>
/// Contains unit tests for the <see cref="GetPathRootQueryValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetPathRootQueryValidatorTests
{
private readonly GetPathRootQueryValidator _validator;
/// <summary>
/// Initializes a new instance of the <see cref="GetPathRootQueryValidatorTests"/> class.
/// </summary>
public GetPathRootQueryValidatorTests()
{
_validator = new GetPathRootQueryValidator();
}
[Fact]
public void Validate_WhenPathIsNull_ShouldHaveValidationError()
{
// Arrange
GetPathRootQuery query = GetPathRootQueryFixture.CreateGetPathRootQuery();
query = query with { Path = null! };
// Act
TestValidationResult<GetPathRootQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationErrorFor(x => x.Path)
.WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
}
[Fact]
public void Validate_WhenPathIsEmpty_ShouldHaveValidationError()
{
// Arrange
GetPathRootQuery query = GetPathRootQueryFixture.CreateGetPathRootQuery();
query = query with { Path = string.Empty };
// Act
TestValidationResult<GetPathRootQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationErrorFor(x => x.Path)
.WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
}
[Fact]
public void Validate_WhenPathIsWhitespace_ShouldHaveValidationError()
{
// Arrange
GetPathRootQuery query = GetPathRootQueryFixture.CreateGetPathRootQuery();
query = query with { Path = " " };
// Act
TestValidationResult<GetPathRootQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationErrorFor(x => x.Path)
.WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
}
[Fact]
public void Validate_WhenPathIsValid_ShouldNotHaveValidationError()
{
// Arrange
GetPathRootQuery query = GetPathRootQueryFixture.CreateGetPathRootQuery();
query = query with { Path = "/valid/path" };
// Act
TestValidationResult<GetPathRootQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationErrorFor(x => x.Path);
}
}
@@ -0,0 +1,99 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathSeparator;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.GetPathSeparator;
/// <summary>
/// Contains unit tests for the <see cref="GetPathSeparatorQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetPathSeparatorQueryHandlerTests
{
private readonly IPathService _mockPathService;
private readonly GetPathSeparatorQueryHandler _sut;
/// <summary>
/// Initializes a new instance of the <see cref="GetPathSeparatorQueryHandlerTests"/> class.
/// </summary>
public GetPathSeparatorQueryHandlerTests()
{
_mockPathService = Substitute.For<IPathService>();
_sut = new GetPathSeparatorQueryHandler(_mockPathService);
}
[Fact]
public async Task Handle_WhenCalled_ShouldReturnPathSeparatorResponse()
{
// Arrange
GetPathSeparatorQuery query = new();
char expectedSeparator = System.IO.Path.DirectorySeparatorChar;
_mockPathService.PathSeparator.Returns(expectedSeparator);
// Act
PathSeparatorResponse result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.Should().NotBeNull();
result.Separator.Should().Be(expectedSeparator.ToString());
_mockPathService.Received(1);
}
[Theory]
[InlineData('/')]
[InlineData('\\')]
public async Task Handle_WithDifferentSeparators_ShouldReturnCorrectSeparator(char separator)
{
// Arrange
GetPathSeparatorQuery query = new();
_mockPathService.PathSeparator.Returns(separator);
// Act
PathSeparatorResponse result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.Should().NotBeNull();
result.Separator.Should().Be(separator.ToString());
_mockPathService.Received(1);
}
[Fact]
public async Task Handle_WhenCalledMultipleTimes_ShouldReturnSameResult()
{
// Arrange
GetPathSeparatorQuery query = new();
char expectedSeparator = System.IO.Path.DirectorySeparatorChar;
_mockPathService.PathSeparator.Returns(expectedSeparator);
// Act
PathSeparatorResponse result1 = await _sut.Handle(query, CancellationToken.None);
PathSeparatorResponse result2 = await _sut.Handle(query, CancellationToken.None);
// Assert
result1.Should().BeEquivalentTo(result2);
_mockPathService.Received(2);
}
[Fact]
public async Task Handle_WithCancellationToken_ShouldCompleteSuccessfully()
{
// Arrange
GetPathSeparatorQuery query = new();
using CancellationTokenSource cts = new();
// Act
Func<Task> act = async () => await _sut.Handle(query, cts.Token);
// Assert
await act.Should().NotThrowAsync();
}
}
@@ -0,0 +1,27 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Core.FileSystemManagement.Paths.Queries.ValidatePath;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.ValidatePath.Fixtures;
/// <summary>
/// Fixture class for the <see cref="ValidatePathQuery"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ValidatePathQueryFixure
{
/// <summary>
/// Creates a random valid query to check if paths exist.
/// </summary>
/// <returns>The created query.</returns>
public static ValidatePathQuery CreateValidatePathQuery()
{
return new Faker<ValidatePathQuery>()
.CustomInstantiator(f => new ValidatePathQuery(
default!
))
.RuleFor(x => x.Path, f => f.System.FilePath());
}
}
@@ -0,0 +1,92 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Application.Core.FileSystemManagement.Paths.Queries.ValidatePath;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.ValidatePath.Fixtures;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services;
using NSubstitute;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.ValidatePath;
/// <summary>
/// Contains unit tests for the <see cref="ValidatePathQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ValidatePathQueryHandlerTests
{
private readonly IPathService _mockPathService;
private readonly ValidatePathQueryHandler _sut;
/// <summary>
/// Initializes a new instance of the <see cref="ValidatePathQueryHandlerTests"/> class.
/// </summary>
public ValidatePathQueryHandlerTests()
{
_mockPathService = Substitute.For<IPathService>();
_sut = new ValidatePathQueryHandler(_mockPathService);
}
[Fact]
public async Task Handle_WhenCalledWithValidPath_ShouldReturnTrueResponse()
{
// Arrange
ValidatePathQuery query = ValidatePathQueryFixure.CreateValidatePathQuery();
_mockPathService.IsValidPath(query.Path!).Returns(true);
// Act
PathValidResponse result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsValid.Should().BeTrue();
_mockPathService.Received(1).IsValidPath(query.Path!);
}
[Fact]
public async Task Handle_WhenCalledWithInvalidPath_ShouldReturnFalseResponse()
{
// Arrange
ValidatePathQuery query = ValidatePathQueryFixure.CreateValidatePathQuery();
_mockPathService.IsValidPath(query.Path!).Returns(false);
// Act
PathValidResponse result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsValid.Should().BeFalse();
_mockPathService.Received(1).IsValidPath(query.Path!);
}
[Fact]
public async Task Handle_WhenCalledWithNullPath_ShouldReturnFalseResponse()
{
// Arrange
ValidatePathQuery query = new(null!);
_mockPathService.IsValidPath(Arg.Any<string>()).Returns(false);
// Act
PathValidResponse result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsValid.Should().BeFalse();
_mockPathService.Received(1).IsValidPath(Arg.Any<string>());
}
[Fact]
public async Task Handle_WhenCalledWithEmptyPath_ShouldReturnFalseResponse()
{
// Arrange
ValidatePathQuery query = new(string.Empty);
_mockPathService.IsValidPath(Arg.Any<string>()).Returns(false);
// Act
PathValidResponse result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsValid.Should().BeFalse();
_mockPathService.Received(1).IsValidPath(Arg.Any<string>());
}
}
@@ -0,0 +1,85 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation.TestHelper;
using Lumina.Application.Core.FileSystemManagement.Paths.Queries.ValidatePath;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.ValidatePath.Fixtures;
using Lumina.Domain.Common.Errors;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.ValidatePath;
/// <summary>
/// Contains unit tests for the <see cref="ValidatePathQueryValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ValidatePathQueryValidatorTests
{
private readonly ValidatePathQueryValidator _validator;
/// <summary>
/// Initializes a new instance of the <see cref="ValidatePathQueryValidatorTests"/> class.
/// </summary>
public ValidatePathQueryValidatorTests()
{
_validator = new ValidatePathQueryValidator();
}
[Fact]
public void Validate_WhenPathIsNull_ShouldHaveValidationError()
{
// Arrange
ValidatePathQuery query = ValidatePathQueryFixure.CreateValidatePathQuery();
query = query with { Path = null! };
// Act
TestValidationResult<ValidatePathQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationErrorFor(x => x.Path)
.WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
}
[Fact]
public void Validate_WhenPathIsEmpty_ShouldHaveValidationError()
{
// Arrange
ValidatePathQuery query = ValidatePathQueryFixure.CreateValidatePathQuery();
query = query with { Path = string.Empty };
// Act
TestValidationResult<ValidatePathQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationErrorFor(x => x.Path)
.WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
}
[Fact]
public void Validate_WhenPathIsWhitespace_ShouldHaveValidationError()
{
// Arrange
ValidatePathQuery query = ValidatePathQueryFixure.CreateValidatePathQuery();
query = query with { Path = " " };
// Act
TestValidationResult<ValidatePathQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationErrorFor(x => x.Path)
.WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
}
[Fact]
public void Validate_WhenPathIsValid_ShouldNotHaveValidationError()
{
// Arrange
ValidatePathQuery query = ValidatePathQueryFixure.CreateValidatePathQuery();
query = query with { Path = "/valid/path" };
// Act
TestValidationResult<ValidatePathQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationErrorFor(x => x.Path);
}
}
@@ -0,0 +1,30 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Contracts.Enums.PhotoLibrary;
using Lumina.Contracts.Responses.FileSystemManagement.Thumbnails;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Thumbnails.Fixtures;
/// <summary>
/// Fixture class for the <see cref="ThumbnailResponse"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ThumbnailResponseFixture
{
/// <summary>
/// Creates a random valid query to get a thumbnail.
/// </summary>
/// <returns>The created query.</returns>
public static ThumbnailResponse CreateThumbnailResponse()
{
return new Faker<ThumbnailResponse>()
.CustomInstantiator(f => new ThumbnailResponse(
default,
default!
))
.RuleFor(x => x.Type, f => f.PickRandom<ImageType>())
.RuleFor(x => x.Bytes, f => f.Random.Bytes(20));
}
}
@@ -0,0 +1,29 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Core.FileSystemManagement.Thumbnails.Queries.GetThumbnail;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Thumbnails.Queries.GetThumbnail.Fixtures;
/// <summary>
/// Fixture class for the <see cref="GetThumbnailQuery"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetThumbnailQueryFixture
{
/// <summary>
/// Creates a random valid query to get a thumbnail.
/// </summary>
/// <returns>The created query.</returns>
public static GetThumbnailQuery CreateGetThumbnailQuery()
{
return new Faker<GetThumbnailQuery>()
.CustomInstantiator(f => new GetThumbnailQuery(
default!,
default
))
.RuleFor(x => x.Path, f => f.System.FilePath())
.RuleFor(x => x.Quality, f => f.Random.Int());
}
}
@@ -0,0 +1,90 @@
#region ========================================================================= USING =====================================================================================
using AutoFixture;
using AutoFixture.AutoNSubstitute;
using ErrorOr;
using FluentAssertions;
using Lumina.Application.Core.FileSystemManagement.Thumbnails.Queries.GetThumbnail;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Thumbnails.Fixtures;
using Lumina.Contracts.Responses.FileSystemManagement.Thumbnails;
using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.Services;
using Lumina.Domain.Core.Aggregates.FileSystemManagement.FileSystemManagementAggregate.ValueObjects;
using NSubstitute;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Thumbnails.Queries.GetThumbnail;
/// <summary>
/// Contains unit tests for the <see cref="GetThumbnailQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetThumbnailQueryHandlerTests
{
private readonly IFixture _fixture;
private readonly IThumbnailService _mockThumbnailService;
private readonly GetThumbnailQueryHandler _sut;
public GetThumbnailQueryHandlerTests()
{
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
_mockThumbnailService = Substitute.For<IThumbnailService>();
_sut = new GetThumbnailQueryHandler(_mockThumbnailService);
}
[Fact]
public async Task Handle_WhenCalledWithValidQuery_ShouldReturnSuccessResult()
{
// Arrange
GetThumbnailQuery query = _fixture.Create<GetThumbnailQuery>();
Thumbnail thumbnail = _fixture.Create<Thumbnail>();
_mockThumbnailService.GetThumbnailAsync(query.Path!, query.Quality, Arg.Any<CancellationToken>())
.Returns(ErrorOrFactory.From(thumbnail));
// Act
ErrorOr<ThumbnailResponse> result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().NotBeNull();
result.Value.Type.Should().Be(thumbnail.Type);
result.Value.Bytes.Should().BeEquivalentTo(thumbnail.Bytes);
await _mockThumbnailService.Received(1).GetThumbnailAsync(query.Path!, query.Quality, Arg.Any<CancellationToken>());
}
[Fact]
public async Task Handle_WhenThumbnailServiceReturnsError_ShouldReturnFailureResult()
{
// Arrange
GetThumbnailQuery query = _fixture.Create<GetThumbnailQuery>();
Error error = Error.Failure("ThumbnailService.Error", "An error occurred");
_mockThumbnailService.GetThumbnailAsync(query.Path!, query.Quality, Arg.Any<CancellationToken>())
.Returns(error);
// Act
ErrorOr<ThumbnailResponse> result = await _sut.Handle(query, CancellationToken.None);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(error);
await _mockThumbnailService.Received(1).GetThumbnailAsync(query.Path!, query.Quality, Arg.Any<CancellationToken>());
}
[Fact]
public async Task Handle_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
GetThumbnailQuery query = _fixture.Create<GetThumbnailQuery>();
CancellationTokenSource cts = new();
cts.Cancel();
_mockThumbnailService.GetThumbnailAsync(query.Path!, query.Quality, cts.Token)
.Returns(Task.FromCanceled<ErrorOr<Thumbnail>>(cts.Token));
// Act & Assert
await Assert.ThrowsAsync<TaskCanceledException>(() => _sut.Handle(query, cts.Token).AsTask());
await _mockThumbnailService.Received(1).GetThumbnailAsync(query.Path!, query.Quality, cts.Token);
}
}
@@ -0,0 +1,104 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation.TestHelper;
using Lumina.Application.Core.FileSystemManagement.Thumbnails.Queries.GetThumbnail;
using Lumina.Domain.Common.Errors;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Thumbnails.Queries.GetThumbnail;
/// <summary>
/// Contains unit tests for the <see cref="GetThumbnailQueryValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetThumbnailQueryValidatorTests
{
private readonly GetThumbnailQueryValidator _validator;
/// <summary>
/// Initializes a new instance of the <see cref="GetThumbnailQueryValidatorTests"/> class.
/// </summary>
public GetThumbnailQueryValidatorTests()
{
_validator = new GetThumbnailQueryValidator();
}
[Fact]
public void Validate_WhenPathIsNull_ShouldHaveValidationError()
{
// Arrange
GetThumbnailQuery query = new(null!, 1);
// Act
TestValidationResult<GetThumbnailQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationErrorFor(x => x.Path).WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
}
[Fact]
public void Validate_WhenPathIsEmpty_ShouldHaveValidationError()
{
// Arrange
GetThumbnailQuery query = new(string.Empty, 1);
// Act
TestValidationResult<GetThumbnailQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationErrorFor(x => x.Path).WithErrorMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
}
[Fact]
public void Validate_WhenPathIsValid_ShouldNotHaveValidationError()
{
// Arrange
GetThumbnailQuery query = new("test", 1);
// Act
TestValidationResult<GetThumbnailQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationErrorFor(x => x.Path);
}
[Fact]
public void Validate_WhenQualityIsNegative_ShouldHaveValidationError()
{
// Arrange
GetThumbnailQuery query = new("test", -1);
// Act
TestValidationResult<GetThumbnailQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationErrorFor(x => x.Quality).WithErrorMessage(Errors.Thumbnails.ImageQaulityMustBeBetweenZeroAndOneHundred.Description);
}
[Fact]
public void Validate_WhenQualityIsOver100_ShouldHaveValidationError()
{
// Arrange
GetThumbnailQuery query = new("test", 101);
// Act
TestValidationResult<GetThumbnailQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationErrorFor(x => x.Quality).WithErrorMessage(Errors.Thumbnails.ImageQaulityMustBeBetweenZeroAndOneHundred.Description);
}
[Fact]
public void Validate_WhenQualityIsValid_ShouldNotHaveValidationError()
{
// Arrange
GetThumbnailQuery query = new("test", 1);
// Act
TestValidationResult<GetThumbnailQuery> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationErrorFor(x => x.Quality);
}
}