diff --git a/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/DirectoriesController.cs b/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/DirectoriesController.cs index 284e289d..c9cbc22b 100644 --- a/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/DirectoriesController.cs +++ b/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/DirectoriesController.cs @@ -51,7 +51,7 @@ public class DirectoriesController : ApiController ErrorOr> result = await _mediator.Send(new GetDirectoryTreeQuery(path, includeFiles, includeHiddenElements), cancellationToken).ConfigureAwait(false); if (!result.IsError && result.Value is not null) { - foreach (FileSystemTreeNodeResponse treeNode in result.Value ?? []) + foreach (FileSystemTreeNodeResponse treeNode in result.Value) { if (cancellationToken.IsCancellationRequested) yield break; @@ -73,7 +73,7 @@ public class DirectoriesController : ApiController ErrorOr> result = await _mediator.Send(new GetTreeDirectoriesQuery(path,includeHiddenElements), cancellationToken).ConfigureAwait(false); if (!result.IsError && result.Value is not null) { - foreach (FileSystemTreeNodeResponse directory in result.Value ?? []) + foreach (FileSystemTreeNodeResponse directory in result.Value) { if (cancellationToken.IsCancellationRequested) yield break; @@ -95,7 +95,7 @@ public class DirectoriesController : ApiController ErrorOr> result = await _mediator.Send(new GetDirectoriesQuery(path, includeHiddenElements), cancellationToken).ConfigureAwait(false); if (!result.IsError && result.Value is not null) { - foreach (DirectoryResponse directory in result.Value ?? []) + foreach (DirectoryResponse directory in result.Value) { if (cancellationToken.IsCancellationRequested) yield break; diff --git a/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/FilesController.cs b/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/FilesController.cs index 18d23db4..f91c83c4 100644 --- a/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/FilesController.cs +++ b/src/Lumina.Presentation.Api/Core/Controllers/FileManagement/FilesController.cs @@ -48,11 +48,14 @@ public class FilesController : ApiController [FromQuery] bool includeHiddenElements, [EnumeratorCancellation] CancellationToken cancellationToken) { ErrorOr> result = await _mediator.Send(new GetTreeFilesQuery(path, includeHiddenElements), cancellationToken).ConfigureAwait(false); - foreach (FileSystemTreeNodeResponse file in result.Value ?? []) + if (!result.IsError && result.Value is not null) { - if (cancellationToken.IsCancellationRequested) - yield break; - yield return file; + foreach (FileSystemTreeNodeResponse file in result.Value) + { + if (cancellationToken.IsCancellationRequested) + yield break; + yield return file; + } } } @@ -67,9 +70,9 @@ public class FilesController : ApiController [FromQuery] bool includeHiddenElements, [EnumeratorCancellation] CancellationToken cancellationToken) { ErrorOr> result = await _mediator.Send(new GetFilesQuery(path, includeHiddenElements), cancellationToken).ConfigureAwait(false); - if (!result.IsError) + if (!result.IsError && result.Value is not null) { - foreach (FileResponse file in result.Value ?? []) + foreach (FileResponse file in result.Value) { if (cancellationToken.IsCancellationRequested) yield break; diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/DirectoriesControllerTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/DirectoriesControllerTests.cs new file mode 100644 index 00000000..77f625a9 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/DirectoriesControllerTests.cs @@ -0,0 +1,234 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using AutoFixture.AutoNSubstitute; +using ErrorOr; +using FluentAssertions; +using Lumina.Application.Core.FileManagement.Directories.Queries.GetDirectories; +using Lumina.Application.Core.FileManagement.Directories.Queries.GetDirectoryTree; +using Lumina.Application.Core.FileManagement.Directories.Queries.GetTreeDirectories; +using Lumina.Contracts.Responses.FileManagement; +using Lumina.Domain.Common.Errors; +using Lumina.Presentation.Api.Core.Controllers.FileManagement; +using Lumina.Presentation.Api.UnitTests.Core.Controllers.FileManagement.Fixtures; +using Mediator; +using NSubstitute; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Controllers.FileManagement; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DirectoriesControllerTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly IFixture _fixture; + private readonly ISender _mockMediator; + private readonly DirectoriesController _sut; + private readonly FileSystemTreeNodeResponseFixture _fileSystemTreeNodeResponseFixture; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public DirectoriesControllerTests() + { + _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); + _mockMediator = Substitute.For(); + _sut = new DirectoriesController(_mockMediator); + _fileSystemTreeNodeResponseFixture = new FileSystemTreeNodeResponseFixture(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public async Task GetDirectoryTree_WhenCalled_ShouldReturnFileSystemTreeNodeResponses() + { + // Arrange + string path = @"C:\TestDir"; + bool includeFiles = true; + bool includeHiddenElements = false; + CancellationToken cancellationToken = CancellationToken.None; + + List expectedResponses = _fileSystemTreeNodeResponseFixture.CreateMany(3, 3, 5); + _mockMediator.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(expectedResponses.AsEnumerable())); + + // Act + IAsyncEnumerable result = _sut.GetDirectoryTree(path, includeFiles, includeHiddenElements, cancellationToken); + + // Assert + List actualResponses = await result.ToListAsync(cancellationToken); + actualResponses.Should().BeEquivalentTo(expectedResponses); + } + + [Fact] + public async Task GetDirectoryTree_WhenMediatorReturnsError_ShouldReturnEmptyEnumerable() + { + // Arrange + string path = @"C:\TestDir"; + bool includeFiles = true; + bool includeHiddenElements = false; + CancellationToken cancellationToken = CancellationToken.None; + + _mockMediator.Send(Arg.Any(), Arg.Any()) + .Returns(Errors.FileManagement.DirectoryNotFound); + + // Act + IAsyncEnumerable result = _sut.GetDirectoryTree(path, includeFiles, includeHiddenElements, cancellationToken); + + // Assert + List actualResponses = await result.ToListAsync(cancellationToken); + actualResponses.Should().BeEmpty(); + } + + [Fact] + public async Task GetTreeDirectories_WhenCalled_ShouldReturnFileSystemTreeNodeResponses() + { + // Arrange + string path = @"C:\TestDir"; + bool includeHiddenElements = false; + CancellationToken cancellationToken = CancellationToken.None; + + List expectedResponses = _fileSystemTreeNodeResponseFixture.CreateMany(3, 3, 5); + _mockMediator.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(expectedResponses.AsEnumerable())); + + // Act + IAsyncEnumerable result = _sut.GetTreeDirectories(path, includeHiddenElements, cancellationToken); + + // Assert + List actualResponses = await result.ToListAsync(cancellationToken); + actualResponses.Should().BeEquivalentTo(expectedResponses); + } + + [Fact] + public async Task GetTreeDirectories_WhenMediatorReturnsError_ShouldReturnEmptyEnumerable() + { + // Arrange + string path = @"C:\TestDir"; + bool includeHiddenElements = false; + CancellationToken cancellationToken = CancellationToken.None; + + _mockMediator.Send(Arg.Any(), Arg.Any()) + .Returns(Errors.FileManagement.DirectoryNotFound); + + // Act + IAsyncEnumerable result = _sut.GetTreeDirectories(path, includeHiddenElements, cancellationToken); + + // Assert + List actualResponses = await result.ToListAsync(cancellationToken); + actualResponses.Should().BeEmpty(); + } + + [Fact] + public async Task GetDirectories_WhenCalled_ShouldReturnDirectoryResponses() + { + // Arrange + string path = @"C:\TestDir"; + bool includeHiddenElements = false; + CancellationToken cancellationToken = CancellationToken.None; + + List expectedResponses = _fixture.CreateMany(3).ToList(); + _mockMediator.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(expectedResponses.AsEnumerable())); + + // Act + IAsyncEnumerable result = _sut.GetDirectories(path, includeHiddenElements, cancellationToken); + + // Assert + List actualResponses = await result.ToListAsync(cancellationToken); + actualResponses.Should().BeEquivalentTo(expectedResponses); + } + + [Fact] + public async Task GetDirectories_WhenMediatorReturnsError_ShouldReturnEmptyEnumerable() + { + // Arrange + string path = @"C:\TestDir"; + bool includeHiddenElements = false; + CancellationToken cancellationToken = CancellationToken.None; + + _mockMediator.Send(Arg.Any(), Arg.Any()) + .Returns(Errors.FileManagement.DirectoryNotFound); + + // Act + IAsyncEnumerable result = _sut.GetDirectories(path, includeHiddenElements, cancellationToken); + + // Assert + List actualResponses = await result.ToListAsync(cancellationToken); + actualResponses.Should().BeEmpty(); + } + + [Fact] + public async Task GetDirectoryTree_WhenCancellationRequested_ShouldCancelEnumeration() + { + // Arrange + string path = @"C:\TestDir"; + bool includeFiles = true; + bool includeHiddenElements = false; + CancellationTokenSource cts = new(); + + List expectedResponses = _fileSystemTreeNodeResponseFixture.CreateMany(100, 3, 5); + _mockMediator.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(expectedResponses.AsEnumerable())); + + // Act + IAsyncEnumerable result = _sut.GetDirectoryTree(path, includeFiles, includeHiddenElements, cts.Token); + cts.Cancel(); + + // Assert + List actualResponses = await result.ToListAsync(); + actualResponses.Should().BeEmpty(); + } + + [Fact] + public async Task GetTreeDirectories_WhenCalled_ShouldCancelEnumerationWhenCancellationRequested() + { + // Arrange + string path = @"C:\TestDir"; + bool includeHiddenElements = false; + CancellationTokenSource cts = new(); + + List expectedResponses = _fileSystemTreeNodeResponseFixture.CreateMany(100, 3, 5); + _mockMediator.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(expectedResponses.AsEnumerable())); + + // Act + IAsyncEnumerable result = _sut.GetTreeDirectories(path, includeHiddenElements, cts.Token); + cts.Cancel(); + + // Assert + List actualResponses = await result.ToListAsync(); + actualResponses.Should().BeEmpty(); + } + + [Fact] + public async Task GetDirectories_WhenCancellationRequested_ShouldCancelEnumeration() + { + // Arrange + string path = @"C:\TestDir"; + bool includeHiddenElements = false; + CancellationTokenSource cts = new(); + + List expectedResponses = _fixture.CreateMany(100).ToList(); + _mockMediator.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(expectedResponses.AsEnumerable())); + + // Act + IAsyncEnumerable result = _sut.GetDirectories(path, includeHiddenElements, cts.Token); + cts.Cancel(); + + // Assert + List actualResponses = await result.ToListAsync(); + actualResponses.Should().BeEmpty(); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/DrivesControllerTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/DrivesControllerTests.cs new file mode 100644 index 00000000..2b259904 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/DrivesControllerTests.cs @@ -0,0 +1,146 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FluentAssertions; +using Lumina.Application.Core.FileManagement.Drives.Queries.GetDrives; +using Lumina.Contracts.Responses.FileManagement; +using Lumina.Presentation.Api.Common.Http; +using Lumina.Presentation.Api.Core.Controllers.FileManagement; +using Lumina.Presentation.Api.UnitTests.Core.Controllers.FileManagement.Fixtures; +using Mediator; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Infrastructure; +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.Presentation.Api.UnitTests.Core.Controllers.FileManagement; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DrivesControllerTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly ISender _mockMediator; + private readonly DrivesController _sut; + private readonly FileSystemTreeNodeResponseFixture _fileSystemTreeNodeResponseFixture; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public DrivesControllerTests() + { + _mockMediator = Substitute.For(); + _sut = new DrivesController(_mockMediator); + _fileSystemTreeNodeResponseFixture = new FileSystemTreeNodeResponseFixture(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public async Task GetDrives_WhenCalled_ShouldReturnOkResultWithFileSystemTreeNodeResponses() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + List expectedResponses = _fileSystemTreeNodeResponseFixture.CreateMany(3, 1, 1); + _mockMediator.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(expectedResponses.AsEnumerable())); + + // Act + IActionResult result = await _sut.GetDrives(cancellationToken); + + // Assert + OkObjectResult okResult = result.Should().BeOfType().Subject; + IEnumerable actualResponses = okResult.Value.Should().BeAssignableTo>().Subject; + actualResponses.Should().BeEquivalentTo(expectedResponses); + } + + [Fact] + public async Task GetDrives_WhenMediatorReturnsError_ShouldReturnProblemResult() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.NotFound("Drive.NotFound", "The requested drive was not found."); + _mockMediator.Send(Arg.Any(), Arg.Any()) + .Returns(expectedError); + HttpContext mockHttpContext = Substitute.For(); + Dictionary mockItems = []; + mockHttpContext.Items.Returns(mockItems!); + _sut.ControllerContext = new ControllerContext + { + HttpContext = mockHttpContext + }; + ProblemDetailsFactory mockProblemDetailsFactory = Substitute.For(); + mockProblemDetailsFactory.CreateProblemDetails( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any()) + .Returns(new ProblemDetails + { + Status = StatusCodes.Status404NotFound, + Title = ErrorType.NotFound.ToString(), + Detail = "The requested drive was not found." + }); + _sut.ProblemDetailsFactory = mockProblemDetailsFactory; + + // Act + IActionResult result = await _sut.GetDrives(cancellationToken); + + // Assert + ObjectResult objectResult = result.Should().BeOfType().Subject; + objectResult.StatusCode.Should().Be(StatusCodes.Status404NotFound); + + ProblemDetails problemDetails = objectResult.Value.Should().BeOfType().Subject; + problemDetails.Title.Should().Be(ErrorType.NotFound.ToString()); + problemDetails.Detail.Should().Be("The requested drive was not found."); + problemDetails.Status.Should().Be(StatusCodes.Status404NotFound); + mockItems.Should().ContainKey(HttpContextItemKeys.ERRORS); + mockItems[HttpContextItemKeys.ERRORS].Should().BeEquivalentTo(new List { expectedError }); + } + + [Fact] + public async Task GetDrives_WhenCalled_ShouldSendGetDrivesQueryToMediator() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockMediator.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(Enumerable.Empty())); + + // Act + await _sut.GetDrives(cancellationToken); + + // Assert + await _mockMediator.Received(1).Send(Arg.Any(), Arg.Is(cancellationToken)); + } + + [Fact] + public async Task GetDrives_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + CancellationTokenSource cts = new(); + + _mockMediator.Send(Arg.Any(), Arg.Any()) + .Returns(callInfo => new ValueTask>>(Task.Run(async () => + { + await Task.Delay(100, callInfo.Arg()); + return ErrorOrFactory.From(_fileSystemTreeNodeResponseFixture.CreateMany(3, 1, 1).AsEnumerable()); + }, callInfo.Arg()))); + + // Act & Assert + cts.CancelAfter(50); + await Assert.ThrowsAnyAsync(() => _sut.GetDrives(cts.Token)); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/FileSystemControllerTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/FileSystemControllerTests.cs new file mode 100644 index 00000000..4299777d --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/FileSystemControllerTests.cs @@ -0,0 +1,122 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using AutoFixture.AutoNSubstitute; +using ErrorOr; +using FluentAssertions; +using Lumina.Application.Core.FileManagement.Directories.Queries.GetDirectories; +using Lumina.Application.Core.FileManagement.Directories.Queries.GetDirectoryTree; +using Lumina.Application.Core.FileManagement.Directories.Queries.GetTreeDirectories; +using Lumina.Application.Core.FileManagement.FileSystem.Queries.GetFileSystem; +using Lumina.Contracts.Enums.FileSystem; +using Lumina.Contracts.Responses.FileManagement; +using Lumina.Domain.Common.Errors; +using Lumina.Presentation.Api.Core.Controllers.FileManagement; +using Lumina.Presentation.Api.UnitTests.Core.Controllers.FileManagement.Fixtures; +using Mediator; +using Microsoft.AspNetCore.Mvc; +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.Presentation.Api.UnitTests.Core.Controllers.FileManagement; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class FileSystemControllerTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly ISender _mockMediator; + private readonly FileSystemController _sut; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public FileSystemControllerTests() + { + _mockMediator = Substitute.For(); + _sut = new FileSystemController(_mockMediator); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public async Task GetType_WhenCalled_ShouldReturnOkResultWithFileSystemTypeResponse() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + FileSystemTypeResponse expectedResponse = new FileSystemTypeResponse(PlatformType.Windows); + _mockMediator.Send(Arg.Any(), Arg.Any()) + .Returns(expectedResponse); + + // Act + IActionResult result = await _sut.GetType(cancellationToken); + + // Assert + OkObjectResult okResult = result.Should().BeOfType().Subject; + FileSystemTypeResponse actualResponse = okResult.Value.Should().BeAssignableTo().Subject; + actualResponse.Should().BeEquivalentTo(expectedResponse); + } + + [Theory] + [InlineData(PlatformType.Windows)] + [InlineData(PlatformType.Unix)] + public async Task GetType_WithDifferentPlatformTypes_ShouldReturnCorrectResponse(PlatformType platformType) + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + FileSystemTypeResponse expectedResponse = new FileSystemTypeResponse(platformType); + _mockMediator.Send(Arg.Any(), Arg.Any()) + .Returns(expectedResponse); + + // Act + IActionResult result = await _sut.GetType(cancellationToken); + + // Assert + OkObjectResult okResult = result.Should().BeOfType().Subject; + FileSystemTypeResponse actualResponse = okResult.Value.Should().BeAssignableTo().Subject; + actualResponse.PlatformType.Should().Be(platformType); + } + + [Fact] + public async Task GetType_WhenCalled_ShouldSendGetFileSystemQueryToMediator() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockMediator.Send(Arg.Any(), Arg.Any()) + .Returns(new FileSystemTypeResponse(PlatformType.Windows)); + + // Act + await _sut.GetType(cancellationToken); + + // Assert + await _mockMediator.Received(1).Send(Arg.Any(), Arg.Is(cancellationToken)); + } + + [Fact] + public async Task GetType_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + CancellationTokenSource cts = new(); + + _mockMediator.Send(Arg.Any(), Arg.Any()) + .Returns(callInfo => new ValueTask(Task.Run(async () => + { + await Task.Delay(100, callInfo.Arg()); + return new FileSystemTypeResponse(PlatformType.Windows); + }, callInfo.Arg()))); + + // Act & Assert + cts.CancelAfter(50); + await Assert.ThrowsAnyAsync(() => _sut.GetType(cts.Token)); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/FilesControllerTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/FilesControllerTests.cs new file mode 100644 index 00000000..b1282a00 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/FilesControllerTests.cs @@ -0,0 +1,171 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using AutoFixture.AutoNSubstitute; +using ErrorOr; +using FluentAssertions; +using Lumina.Application.Core.FileManagement.Files.Queries.GetFiles; +using Lumina.Application.Core.FileManagement.Files.Queries.GetTreeFiles; +using Lumina.Contracts.Responses.FileManagement; +using Lumina.Domain.Common.Errors; +using Lumina.Presentation.Api.Core.Controllers.FileManagement; +using Lumina.Presentation.Api.UnitTests.Core.Controllers.FileManagement.Fixtures; +using Mediator; +using NSubstitute; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + + +namespace Lumina.Presentation.Api.UnitTests.Core.Controllers.FileManagement; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class FilesControllerTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly IFixture _fixture; + private readonly ISender _mockMediator; + private readonly FilesController _sut; + private readonly FileSystemTreeNodeResponseFixture _fileSystemTreeNodeResponseFixture; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public FilesControllerTests() + { + _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); + _mockMediator = Substitute.For(); + _sut = new FilesController(_mockMediator); + _fileSystemTreeNodeResponseFixture = new FileSystemTreeNodeResponseFixture(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public async Task GetTreeFiles_WhenCalled_ShouldReturnFileSystemTreeNodeResponses() + { + // Arrange + string path = @"C:\TestDir"; + bool includeHiddenElements = false; + CancellationToken cancellationToken = CancellationToken.None; + + List expectedResponses = _fileSystemTreeNodeResponseFixture.CreateMany(3, 3, 5); + _mockMediator.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(expectedResponses.AsEnumerable())); + + // Act + IAsyncEnumerable result = _sut.GetTreeFiles(path, includeHiddenElements, cancellationToken); + + // Assert + List actualResponses = await result.ToListAsync(cancellationToken); + actualResponses.Should().BeEquivalentTo(expectedResponses); + } + + [Fact] + public async Task GetTreeFiles_WhenMediatorReturnsError_ShouldReturnEmptyEnumerable() + { + // Arrange + string path = @"C:\TestDir"; + bool includeHiddenElements = false; + CancellationToken cancellationToken = CancellationToken.None; + + _mockMediator.Send(Arg.Any(), Arg.Any()) + .Returns(Errors.FileManagement.DirectoryNotFound); + + // Act + IAsyncEnumerable result = _sut.GetTreeFiles(path, includeHiddenElements, cancellationToken); + + // Assert + List actualResponses = await result.ToListAsync(cancellationToken); + actualResponses.Should().BeEmpty(); + } + + [Fact] + public async Task GetFiles_WhenCalled_ShouldReturnFileResponses() + { + // Arrange + string path = @"C:\TestDir"; + bool includeHiddenElements = false; + CancellationToken cancellationToken = CancellationToken.None; + + List expectedResponses = _fixture.CreateMany(3).ToList(); + _mockMediator.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(expectedResponses.AsEnumerable())); + + // Act + IAsyncEnumerable result = _sut.GetFiles(path, includeHiddenElements, cancellationToken); + + // Assert + List actualResponses = await result.ToListAsync(cancellationToken); + actualResponses.Should().BeEquivalentTo(expectedResponses); + } + + [Fact] + public async Task GetFiles_WhenMediatorReturnsError_ShouldReturnEmptyEnumerable() + { + // Arrange + string path = @"C:\TestDir"; + bool includeHiddenElements = false; + CancellationToken cancellationToken = CancellationToken.None; + + _mockMediator.Send(Arg.Any(), Arg.Any()) + .Returns(Errors.FileManagement.DirectoryNotFound); + + // Act + IAsyncEnumerable result = _sut.GetFiles(path, includeHiddenElements, cancellationToken); + + // Assert + List actualResponses = await result.ToListAsync(cancellationToken); + actualResponses.Should().BeEmpty(); + } + + [Fact] + public async Task GetTreeFiles_WhenCancellationRequested_ShouldCancelEnumeration() + { + // Arrange + string path = @"C:\TestDir"; + bool includeHiddenElements = false; + CancellationTokenSource cts = new(); + + List expectedResponses = _fileSystemTreeNodeResponseFixture.CreateMany(100, 3, 5); + _mockMediator.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(expectedResponses.AsEnumerable())); + + // Act + IAsyncEnumerable result = _sut.GetTreeFiles(path, includeHiddenElements, cts.Token); + cts.Cancel(); + + // Assert + List actualResponses = await result.ToListAsync(); + actualResponses.Should().BeEmpty(); + } + + [Fact] + public async Task GetFiles_WhenCancellationRequested_ShouldCancelEnumeration() + { + // Arrange + string path = @"C:\TestDir"; + bool includeHiddenElements = false; + CancellationTokenSource cts = new(); + + List expectedResponses = _fixture.CreateMany(100).ToList(); + _mockMediator.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(expectedResponses.AsEnumerable())); + + // Act + IAsyncEnumerable result = _sut.GetFiles(path, includeHiddenElements, cts.Token); + cts.Cancel(); + + // Assert + List actualResponses = await result.ToListAsync(); + actualResponses.Should().BeEmpty(); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/Fixtures/FileSystemTreeNodeResponseFixture.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/Fixtures/FileSystemTreeNodeResponseFixture.cs new file mode 100644 index 00000000..19dbba4e --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/Fixtures/FileSystemTreeNodeResponseFixture.cs @@ -0,0 +1,62 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Enums.FileSystem; +using Lumina.Contracts.Responses.FileManagement; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Controllers.FileManagement.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class FileSystemTreeNodeResponseFixture +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly Faker _faker = new(); + #endregion + + #region ===================================================================== METHODS =================================================================================== + /// + /// Creates a single with a nested structure. + /// + /// The current depth in the tree structure. Default is 0 (root level). + /// The maximum depth of the tree structure. Default is 2. + /// The maximum number of children for each node. Default is 3. + /// A with a nested structure. + 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; + } + + /// + /// Creates a list of objects, each with a nested structure. + /// + /// The number of root-level nodes to create. Default is 2. + /// The maximum depth of the tree structure for each root node. Default is 2. + /// The maximum number of children for each node. Default is 3. + /// A list of objects with nested structures. + public List CreateMany(int count = 2, int maxDepth = 2, int maxChildren = 3) + { + return Enumerable.Range(0, count).Select(_ => Create(0, maxDepth, maxChildren)).ToList(); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/Fixtures/PathSegmentResponseFixture.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/Fixtures/PathSegmentResponseFixture.cs new file mode 100644 index 00000000..97a2d3e5 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/Fixtures/PathSegmentResponseFixture.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.FileManagement; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Controllers.FileManagement.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class PathSegmentResponseFixture +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly Faker _faker = new(); + #endregion + + #region ===================================================================== METHODS =================================================================================== + /// + /// Creates a random valid . + /// + /// The created . + public PathSegmentResponse Create() + { + return new PathSegmentResponse(_faker.System.DirectoryPath()); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return Enumerable.Range(0, count).Select(_ => Create()).ToList(); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/Fixtures/PathSeparatorResponseFixture.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/Fixtures/PathSeparatorResponseFixture.cs new file mode 100644 index 00000000..f754d790 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/Fixtures/PathSeparatorResponseFixture.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.FileManagement; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Controllers.FileManagement.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class PathSeparatorResponseFixture +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly Faker _faker = new(); + #endregion + + #region ===================================================================== METHODS =================================================================================== + /// + /// Creates a random valid . + /// + /// The created . + public PathSeparatorResponse Create() + { + return new PathSeparatorResponse(_faker.System.DirectoryPath()); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return Enumerable.Range(0, count).Select(_ => Create()).ToList(); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/Fixtures/ThumbnailResponseFixture.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/Fixtures/ThumbnailResponseFixture.cs new file mode 100644 index 00000000..2fda7c96 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/Fixtures/ThumbnailResponseFixture.cs @@ -0,0 +1,32 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Enums.PhotoLibrary; +using Lumina.Contracts.Responses.FileManagement; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Controllers.FileManagement.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class ThumbnailResponseFixture +{ + #region ===================================================================== METHODS =================================================================================== + /// + /// Creates a random valid query to get a thumbnail. + /// + /// The created query. + public static ThumbnailResponse CreateThumbnailResponse() + { + return new Faker() + .CustomInstantiator(f => new ThumbnailResponse( + default, + default! + )) + .RuleFor(x => x.Type, f => f.PickRandom()) + .RuleFor(x => x.Bytes, f => f.Random.Bytes(20)); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/PathControllerTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/PathControllerTests.cs new file mode 100644 index 00000000..f6e30333 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/PathControllerTests.cs @@ -0,0 +1,680 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FluentAssertions; +using Lumina.Application.Core.FileManagement.Paths.Commands.CombinePath; +using Lumina.Application.Core.FileManagement.Paths.Commands.SplitPath; +using Lumina.Application.Core.FileManagement.Paths.Queries.CheckPathExists; +using Lumina.Application.Core.FileManagement.Paths.Queries.GetPathParent; +using Lumina.Application.Core.FileManagement.Paths.Queries.GetPathRoot; +using Lumina.Application.Core.FileManagement.Paths.Queries.GetPathSeparator; +using Lumina.Application.Core.FileManagement.Paths.Queries.ValidatePath; +using Lumina.Contracts.Responses.FileManagement; +using Lumina.Presentation.Api.Core.Controllers.FileManagement; +using Lumina.Presentation.Api.UnitTests.Core.Controllers.FileManagement.Fixtures; +using Mediator; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Infrastructure; +using Microsoft.AspNetCore.Mvc.ModelBinding; +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.Presentation.Api.UnitTests.Core.Controllers.FileManagement; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class PathControllerTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly ISender _mockMediator; + private readonly PathController _sut; + private readonly PathSegmentResponseFixture _pathSegmentResponseFixture; + private readonly PathSeparatorResponseFixture _pathSeparatorResponseFixture; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public PathControllerTests() + { + _mockMediator = Substitute.For(); + _sut = new PathController(_mockMediator); + _pathSegmentResponseFixture = new PathSegmentResponseFixture(); + _pathSeparatorResponseFixture = new PathSeparatorResponseFixture(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public async Task GetPathRoot_WhenCalled_ShouldReturnOkResultWithPathSegmentResponse() + { + // Arrange + string path = @"C:\Users\TestUser"; + CancellationToken cancellationToken = CancellationToken.None; + PathSegmentResponse expectedResponse = _pathSegmentResponseFixture.Create(); + _mockMediator.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(expectedResponse)); + + // Act + IActionResult result = await _sut.GetPathRoot(path, cancellationToken); + + // Assert + OkObjectResult okResult = result.Should().BeOfType().Subject; + PathSegmentResponse actualResponse = okResult.Value.Should().BeAssignableTo().Subject; + actualResponse.Should().BeEquivalentTo(expectedResponse); + } + + [Fact] + public async Task GetPathRoot_WhenMediatorReturnsError_ShouldReturnProblemResult() + { + // Arrange + string path = @"InvalidPath"; + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.Validation("Path.Invalid", "The provided path is invalid."); + _mockMediator.Send(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + _sut.ControllerContext = new ControllerContext(); + + ProblemDetailsFactory mockProblemDetailsFactory = Substitute.For(); + mockProblemDetailsFactory.CreateProblemDetails( + Arg.Any(), + Arg.Any(), + Arg.Is(ErrorType.Validation.ToString()), + Arg.Any(), + Arg.Any(), + Arg.Any()) + .Returns(new ProblemDetails + { + Status = StatusCodes.Status400BadRequest, + Title = ErrorType.Validation.ToString(), + Detail = "The provided path is invalid." + }); + _sut.ProblemDetailsFactory = mockProblemDetailsFactory; + ValidationProblemDetails expectedValidationProblemDetails = new() + { + Status = StatusCodes.Status400BadRequest, + Title = "One or more validation errors occurred.", + Errors = + { + { "Path.Invalid", new[] { "The provided path is invalid." } } + } + }; + + mockProblemDetailsFactory.CreateValidationProblemDetails( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any()) + .Returns(expectedValidationProblemDetails); + + // Act + IActionResult result = await _sut.GetPathRoot(path, cancellationToken); + + // Assert + BadRequestObjectResult badRequestResult = result.Should().BeOfType().Subject; + badRequestResult.StatusCode.Should().Be(StatusCodes.Status400BadRequest); + + ValidationProblemDetails actualValidationProblemDetails = badRequestResult.Value.Should().BeOfType().Subject; + actualValidationProblemDetails.Should().BeEquivalentTo(expectedValidationProblemDetails); + } + + [Fact] + public async Task GetPathRoot_WhenCalled_ShouldSendGetPathRootQueryToMediator() + { + // Arrange + string path = @"C:\Users\TestUser"; + CancellationToken cancellationToken = CancellationToken.None; + _mockMediator.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(_pathSegmentResponseFixture.Create())); + + // Act + await _sut.GetPathRoot(path, cancellationToken); + + // Assert + await _mockMediator.Received(1).Send(Arg.Is(q => q.Path == path), Arg.Is(cancellationToken)); + } + + [Fact] + public async Task GetPathRoot_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + string path = @"C:\Users\TestUser"; + CancellationTokenSource cts = new(); + + _mockMediator.Send(Arg.Any(), Arg.Any()) + .Returns(callInfo => new ValueTask>(Task.Run(async () => + { + await Task.Delay(100, callInfo.Arg()); + return ErrorOrFactory.From(_pathSegmentResponseFixture.Create()); + }, callInfo.Arg()))); + + // Act & Assert + cts.CancelAfter(50); + await Assert.ThrowsAnyAsync(() => _sut.GetPathRoot(path, cts.Token)); + } + + [Fact] + public async Task GetPathSeparator_WhenCalled_ShouldReturnOkResultWithPathSeparatorResponse() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + PathSeparatorResponse expectedResponse = _pathSeparatorResponseFixture.Create(); + _mockMediator.Send(Arg.Any(), Arg.Any()) + .Returns(expectedResponse); + + // Act + IActionResult result = await _sut.GetPathSeparator(cancellationToken); + + // Assert + OkObjectResult okResult = result.Should().BeOfType().Subject; + PathSeparatorResponse actualResponse = okResult.Value.Should().BeAssignableTo().Subject; + actualResponse.Should().BeEquivalentTo(expectedResponse); + } + + [Fact] + public async Task GetPathSeparator_WhenCalled_ShouldSendGetPathSeparatorQueryToMediator() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockMediator.Send(Arg.Any(), Arg.Any()) + .Returns(_pathSeparatorResponseFixture.Create()); + + // Act + await _sut.GetPathSeparator(cancellationToken); + + // Assert + await _mockMediator.Received(1).Send(Arg.Any(), Arg.Is(cancellationToken)); + } + + [Fact] + public async Task GetPathSeparator_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + CancellationTokenSource cts = new(); + + _mockMediator.Send(Arg.Any(), Arg.Any()) + .Returns(callInfo => new ValueTask(Task.Run(async () => + { + await Task.Delay(100, callInfo.Arg()); + return _pathSeparatorResponseFixture.Create(); + }, callInfo.Arg()))); + + // Act & Assert + cts.CancelAfter(50); + await Assert.ThrowsAnyAsync(() => _sut.GetPathSeparator(cts.Token)); + } + + [Fact] + public async Task GetPathParent_WhenCalled_ShouldReturnOkResultWithPathSegmentResponses() + { + // Arrange + string path = @"C:\Users\TestUser\Documents"; + CancellationToken cancellationToken = CancellationToken.None; + IEnumerable expectedResponse = + [ + _pathSegmentResponseFixture.Create(), + _pathSegmentResponseFixture.Create() + ]; + _mockMediator.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(expectedResponse)); + + // Act + IActionResult result = await _sut.GetPathParent(path, cancellationToken); + + // Assert + OkObjectResult okResult = result.Should().BeOfType().Subject; + IEnumerable actualResponse = okResult.Value.Should().BeAssignableTo>().Subject; + actualResponse.Should().BeEquivalentTo(expectedResponse); + } + + [Fact] + public async Task GetPathParent_WhenMediatorReturnsError_ShouldReturnProblemResult() + { + // Arrange + string path = @"InvalidPath"; + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.Validation("Path.Invalid", "The provided path is invalid."); + _mockMediator.Send(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + _sut.ControllerContext = new ControllerContext(); + + ProblemDetailsFactory mockProblemDetailsFactory = Substitute.For(); + mockProblemDetailsFactory.CreateProblemDetails( + Arg.Any(), + Arg.Any(), + Arg.Is(ErrorType.Validation.ToString()), + Arg.Any(), + Arg.Any(), + Arg.Any()) + .Returns(new ProblemDetails + { + Status = StatusCodes.Status400BadRequest, + Title = ErrorType.Validation.ToString(), + Detail = "The provided path is invalid." + }); + _sut.ProblemDetailsFactory = mockProblemDetailsFactory; + ValidationProblemDetails expectedValidationProblemDetails = new() + { + Status = StatusCodes.Status400BadRequest, + Title = "One or more validation errors occurred.", + Errors = + { + { "Path.Invalid", new[] { "The provided path is invalid." } } + } + }; + mockProblemDetailsFactory.CreateValidationProblemDetails( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any()) + .Returns(expectedValidationProblemDetails); + + // Act + IActionResult result = await _sut.GetPathParent(path, cancellationToken); + + // Assert + BadRequestObjectResult badRequestResult = result.Should().BeOfType().Subject; + badRequestResult.StatusCode.Should().Be(StatusCodes.Status400BadRequest); + + ValidationProblemDetails actualValidationProblemDetails = badRequestResult.Value.Should().BeOfType().Subject; + actualValidationProblemDetails.Should().BeEquivalentTo(expectedValidationProblemDetails); + } + + [Fact] + public async Task GetPathParent_WhenCalled_ShouldSendGetPathParentQueryToMediator() + { + // Arrange + string path = @"C:\Users\TestUser\Documents"; + CancellationToken cancellationToken = CancellationToken.None; + _mockMediator.Send(Arg.Any(), Arg.Any()) + .Returns(new List { _pathSegmentResponseFixture.Create() }); + + // Act + await _sut.GetPathParent(path, cancellationToken); + + // Assert + await _mockMediator.Received(1).Send(Arg.Is(q => q.Path == path), Arg.Is(cancellationToken)); + } + + [Fact] + public async Task GetPathParent_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + string path = @"C:\Users\TestUser\Documents"; + CancellationTokenSource cts = new(); + + _mockMediator.Send(Arg.Any(), Arg.Any()) + .Returns(callInfo => new ValueTask>>(Task.Run(async () => + { + await Task.Delay(100, callInfo.Arg()); + return ErrorOrFactory.From(new List + { + _pathSegmentResponseFixture.Create() + }.AsEnumerable()); + }, callInfo.Arg()))); + + // Act & Assert + cts.CancelAfter(50); + await Assert.ThrowsAnyAsync(() => _sut.GetPathParent(path, cts.Token)); + } + + [Fact] + public async Task CombinePath_WhenCalled_ShouldReturnOkResultWithPathSegmentResponse() + { + // Arrange + string originalPath = @"C:\Users"; + string newPath = "TestUser"; + CancellationToken cancellationToken = CancellationToken.None; + PathSegmentResponse expectedResponse = _pathSegmentResponseFixture.Create(); + _mockMediator.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(expectedResponse)); + + // Act + IActionResult result = await _sut.CombinePath(originalPath, newPath, cancellationToken); + + // Assert + OkObjectResult okResult = result.Should().BeOfType().Subject; + PathSegmentResponse actualResponse = okResult.Value.Should().BeAssignableTo().Subject; + actualResponse.Should().BeEquivalentTo(expectedResponse); + } + + [Fact] + public async Task CombinePath_WhenMediatorReturnsError_ShouldReturnProblemResult() + { + // Arrange + string originalPath = @"InvalidPath"; + string newPath = "TestUser"; + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.Validation("Path.Invalid", "The provided path is invalid."); + _mockMediator.Send(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + _sut.ControllerContext = new ControllerContext(); + + ProblemDetailsFactory mockProblemDetailsFactory = Substitute.For(); + mockProblemDetailsFactory.CreateProblemDetails( + Arg.Any(), + Arg.Any(), + Arg.Is(ErrorType.Validation.ToString()), + Arg.Any(), + Arg.Any(), + Arg.Any()) + .Returns(new ProblemDetails + { + Status = StatusCodes.Status400BadRequest, + Title = ErrorType.Validation.ToString(), + Detail = "The provided path is invalid." + }); + _sut.ProblemDetailsFactory = mockProblemDetailsFactory; + ValidationProblemDetails expectedValidationProblemDetails = new() + { + Status = StatusCodes.Status400BadRequest, + Title = "One or more validation errors occurred.", + Errors = + { + { "Path.Invalid", new[] { "The provided path is invalid." } } + } + }; + mockProblemDetailsFactory.CreateValidationProblemDetails( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any()) + .Returns(expectedValidationProblemDetails); + + // Act + IActionResult result = await _sut.CombinePath(originalPath, newPath, cancellationToken); + + // Assert + BadRequestObjectResult badRequestResult = result.Should().BeOfType().Subject; + badRequestResult.StatusCode.Should().Be(StatusCodes.Status400BadRequest); + + ValidationProblemDetails actualValidationProblemDetails = badRequestResult.Value.Should().BeOfType().Subject; + actualValidationProblemDetails.Should().BeEquivalentTo(expectedValidationProblemDetails); + } + + [Fact] + public async Task CombinePath_WhenCalled_ShouldSendCombinePathCommandToMediator() + { + // Arrange + string originalPath = @"C:\Users"; + string newPath = "TestUser"; + CancellationToken cancellationToken = CancellationToken.None; + _mockMediator.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(_pathSegmentResponseFixture.Create())); + + // Act + await _sut.CombinePath(originalPath, newPath, cancellationToken); + + // Assert + await _mockMediator.Received(1).Send(Arg.Is(c => c.OriginalPath == originalPath && c.NewPath == newPath), Arg.Is(cancellationToken)); + } + + [Fact] + public async Task CombinePath_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + string originalPath = @"C:\Users"; + string newPath = "TestUser"; + CancellationTokenSource cts = new(); + + _mockMediator.Send(Arg.Any(), Arg.Any()) + .Returns(callInfo => new ValueTask>(Task.Run(async () => + { + await Task.Delay(100, callInfo.Arg()); + return ErrorOrFactory.From(_pathSegmentResponseFixture.Create()); + }, callInfo.Arg()))); + + // Act & Assert + cts.CancelAfter(50); + await Assert.ThrowsAnyAsync(() => _sut.CombinePath(originalPath, newPath, cts.Token)); + } + + [Fact] + public async Task SplitPath_WhenCalled_ShouldReturnOkResultWithPathSegmentResponses() + { + // Arrange + string path = @"C:\Users\TestUser\Documents"; + CancellationToken cancellationToken = CancellationToken.None; + IEnumerable expectedResponse = + [ + _pathSegmentResponseFixture.Create(), + _pathSegmentResponseFixture.Create(), + _pathSegmentResponseFixture.Create() + ]; + _mockMediator.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(expectedResponse)); + + // Act + IActionResult result = await _sut.SplitPath(path, cancellationToken); + + // Assert + OkObjectResult okResult = result.Should().BeOfType().Subject; + IEnumerable actualResponse = okResult.Value.Should().BeAssignableTo>().Subject; + actualResponse.Should().BeEquivalentTo(expectedResponse); + } + + [Fact] + public async Task SplitPath_WhenMediatorReturnsError_ShouldReturnProblemResult() + { + // Arrange + string path = @"InvalidPath"; + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.Validation("Path.Invalid", "The provided path is invalid."); + _mockMediator.Send(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + _sut.ControllerContext = new ControllerContext(); + + ProblemDetailsFactory mockProblemDetailsFactory = Substitute.For(); + mockProblemDetailsFactory.CreateProblemDetails( + Arg.Any(), + Arg.Any(), + Arg.Is(ErrorType.Validation.ToString()), + Arg.Any(), + Arg.Any(), + Arg.Any()) + .Returns(new ProblemDetails + { + Status = StatusCodes.Status400BadRequest, + Title = ErrorType.Validation.ToString(), + Detail = "The provided path is invalid." + }); + _sut.ProblemDetailsFactory = mockProblemDetailsFactory; + ValidationProblemDetails expectedValidationProblemDetails = new() + { + Status = StatusCodes.Status400BadRequest, + Title = "One or more validation errors occurred.", + Errors = + { + { "Path.Invalid", new[] { "The provided path is invalid." } } + } + }; + mockProblemDetailsFactory.CreateValidationProblemDetails( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any()) + .Returns(expectedValidationProblemDetails); + + // Act + IActionResult result = await _sut.SplitPath(path, cancellationToken); + + // Assert + BadRequestObjectResult badRequestResult = result.Should().BeOfType().Subject; + badRequestResult.StatusCode.Should().Be(StatusCodes.Status400BadRequest); + + ValidationProblemDetails actualValidationProblemDetails = badRequestResult.Value.Should().BeOfType().Subject; + actualValidationProblemDetails.Should().BeEquivalentTo(expectedValidationProblemDetails); + } + + [Fact] + public async Task SplitPath_WhenCalled_ShouldSendSplitPathCommandToMediator() + { + // Arrange + string path = @"C:\Users\TestUser\Documents"; + CancellationToken cancellationToken = CancellationToken.None; + _mockMediator.Send(Arg.Any(), Arg.Any()) + .Returns(new List { _pathSegmentResponseFixture.Create() }); + + // Act + await _sut.SplitPath(path, cancellationToken); + + // Assert + await _mockMediator.Received(1).Send(Arg.Is(c => c.Path == path), Arg.Is(cancellationToken)); + } + + [Fact] + public async Task SplitPath_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + string path = @"C:\Users\TestUser\Documents"; + CancellationTokenSource cts = new(); + + _mockMediator.Send(Arg.Any(), Arg.Any()) + .Returns(callInfo => new ValueTask>>(Task.Run(async () => + { + await Task.Delay(100, callInfo.Arg()); + return ErrorOrFactory.From(new List + { + _pathSegmentResponseFixture.Create() + }.AsEnumerable()); + }, callInfo.Arg()))); + + // Act & Assert + cts.CancelAfter(50); + await Assert.ThrowsAnyAsync(() => _sut.SplitPath(path, cts.Token)); + } + + [Fact] + public async Task ValidatePath_WhenCalled_ShouldReturnOkResultWithPathValidResponse() + { + // Arrange + string path = @"C:\Users\TestUser\Documents"; + CancellationToken cancellationToken = CancellationToken.None; + PathValidResponse expectedResponse = new(true); + _mockMediator.Send(Arg.Any(), Arg.Any()) + .Returns(expectedResponse); + + // Act + IActionResult result = await _sut.ValidatePath(path, cancellationToken); + + // Assert + OkObjectResult okResult = result.Should().BeOfType().Subject; + PathValidResponse actualResponse = okResult.Value.Should().BeAssignableTo().Subject; + actualResponse.Should().BeEquivalentTo(expectedResponse); + } + + [Fact] + public async Task ValidatePath_WhenCalled_ShouldSendValidatePathQueryToMediator() + { + // Arrange + string path = @"C:\Users\TestUser\Documents"; + CancellationToken cancellationToken = CancellationToken.None; + _mockMediator.Send(Arg.Any(), Arg.Any()) + .Returns(new PathValidResponse(true)); + + // Act + await _sut.ValidatePath(path, cancellationToken); + + // Assert + await _mockMediator.Received(1).Send(Arg.Is(q => q.Path == path), Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ValidatePath_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + string path = @"C:\Users\TestUser\Documents"; + CancellationTokenSource cts = new(); + + _mockMediator.Send(Arg.Any(), Arg.Any()) + .Returns(callInfo => new ValueTask(Task.Run(async () => + { + await Task.Delay(100, callInfo.Arg()); + return new PathValidResponse(true); + }, callInfo.Arg()))); + + // Act & Assert + cts.CancelAfter(50); + await Assert.ThrowsAnyAsync(() => _sut.ValidatePath(path, cts.Token)); + } + + [Fact] + public async Task CheckPathExists_WhenCalled_ShouldReturnOkResultWithPathExistsResponse() + { + // Arrange + string path = @"C:\Users\TestUser\Documents"; + CancellationToken cancellationToken = CancellationToken.None; + PathExistsResponse expectedResponse = new(true); + _mockMediator.Send(Arg.Any(), Arg.Any()) + .Returns(expectedResponse); + + // Act + IActionResult result = await _sut.CheckPathExists(path, cancellationToken); + + // Assert + OkObjectResult okResult = result.Should().BeOfType().Subject; + PathExistsResponse actualResponse = okResult.Value.Should().BeAssignableTo().Subject; + actualResponse.Should().BeEquivalentTo(expectedResponse); + } + + [Fact] + public async Task CheckPathExists_WhenCalled_ShouldSendCheckPathExistsQueryToMediator() + { + // Arrange + string path = @"C:\Users\TestUser\Documents"; + CancellationToken cancellationToken = CancellationToken.None; + _mockMediator.Send(Arg.Any(), Arg.Any()) + .Returns(new PathExistsResponse(true)); + + // Act + await _sut.CheckPathExists(path, cancellationToken); + + // Assert + await _mockMediator.Received(1).Send(Arg.Is(q => q.Path == path), Arg.Is(cancellationToken)); + } + + [Fact] + public async Task CheckPathExists_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + string path = @"C:\Users\TestUser\Documents"; + CancellationTokenSource cts = new(); + + _mockMediator.Send(Arg.Any(), Arg.Any()) + .Returns(callInfo => new ValueTask(Task.Run(async () => + { + await Task.Delay(100, callInfo.Arg()); + return new PathExistsResponse(true); + }, callInfo.Arg()))); + + // Act & Assert + cts.CancelAfter(50); + await Assert.ThrowsAnyAsync(() => _sut.CheckPathExists(path, cts.Token)); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/ThumbnailsControllerTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/ThumbnailsControllerTests.cs new file mode 100644 index 00000000..47215f91 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Controllers/FileManagement/ThumbnailsControllerTests.cs @@ -0,0 +1,154 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FluentAssertions; +using Lumina.Application.Core.FileManagement.Drives.Queries.GetDrives; +using Lumina.Application.Core.FileManagement.Thumbnails.Queries.GetThumbnail; +using Lumina.Contracts.Responses.FileManagement; +using Lumina.Presentation.Api.Common.Http; +using Lumina.Presentation.Api.Common.Utilities; +using Lumina.Presentation.Api.Core.Controllers.FileManagement; +using Lumina.Presentation.Api.UnitTests.Core.Controllers.FileManagement.Fixtures; +using Mediator; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Infrastructure; +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.Presentation.Api.UnitTests.Core.Controllers.FileManagement; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ThumbnailsControllerTests +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly ISender _mockMediator; + private readonly ThumbnailsController _sut; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public ThumbnailsControllerTests() + { + _mockMediator = Substitute.For(); + _sut = new ThumbnailsController(_mockMediator); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public async Task GetThumbnail_WhenCalled_ShouldReturnFileResultWithThumbnailResponse() + { + // Arrange + string path = "/path/to/file.jpg"; + int quality = 80; + CancellationToken cancellationToken = CancellationToken.None; + ThumbnailResponse expectedResponse = ThumbnailResponseFixture.CreateThumbnailResponse(); + _mockMediator.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(expectedResponse)); + + // Act + IActionResult result = await _sut.GetThumbnail(path, quality, cancellationToken); + + // Assert + FileContentResult fileResult = result.Should().BeOfType().Subject; + fileResult.FileContents.Should().BeEquivalentTo(expectedResponse.Bytes); + fileResult.ContentType.Should().Be(MimeTypes.GetMimeType(expectedResponse.Type)); + } + + [Fact] + public async Task GetThumbnail_WhenMediatorReturnsError_ShouldReturnProblemResult() + { + // Arrange + string path = "/path/to/nonexistent/file.jpg"; + int quality = 80; + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.NotFound("Thumbnail.NotFound", "The requested thumbnail was not found."); + _mockMediator.Send(Arg.Any(), Arg.Any()) + .Returns(expectedError); + HttpContext mockHttpContext = Substitute.For(); + Dictionary mockItems = []; + mockHttpContext.Items.Returns(mockItems!); + _sut.ControllerContext = new ControllerContext + { + HttpContext = mockHttpContext + }; + ProblemDetailsFactory mockProblemDetailsFactory = Substitute.For(); + mockProblemDetailsFactory.CreateProblemDetails( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any()) + .Returns(new ProblemDetails + { + Status = StatusCodes.Status404NotFound, + Title = ErrorType.NotFound.ToString(), + Detail = "The requested thumbnail was not found." + }); + _sut.ProblemDetailsFactory = mockProblemDetailsFactory; + + // Act + IActionResult result = await _sut.GetThumbnail(path, quality, cancellationToken); + + // Assert + ObjectResult objectResult = result.Should().BeOfType().Subject; + objectResult.StatusCode.Should().Be(StatusCodes.Status404NotFound); + + ProblemDetails problemDetails = objectResult.Value.Should().BeOfType().Subject; + problemDetails.Title.Should().Be(ErrorType.NotFound.ToString()); + problemDetails.Detail.Should().Be("The requested thumbnail was not found."); + problemDetails.Status.Should().Be(StatusCodes.Status404NotFound); + mockItems.Should().ContainKey(HttpContextItemKeys.ERRORS); + mockItems[HttpContextItemKeys.ERRORS].Should().BeEquivalentTo(new List { expectedError }); + } + + [Fact] + public async Task GetThumbnail_WhenCalled_ShouldSendGetThumbnailQueryToMediator() + { + // Arrange + string path = "/path/to/file.jpg"; + int quality = 80; + CancellationToken cancellationToken = CancellationToken.None; + _mockMediator.Send(Arg.Any(), Arg.Any()) + .Returns(ErrorOrFactory.From(ThumbnailResponseFixture.CreateThumbnailResponse())); + + // Act + await _sut.GetThumbnail(path, quality, cancellationToken); + + // Assert + await _mockMediator.Received(1).Send(Arg.Is(q => q.Path == path && q.Quality == quality), Arg.Is(cancellationToken)); + } + + [Fact] + public async Task GetThumbnail_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + string path = "/path/to/file.jpg"; + int quality = 80; + CancellationTokenSource cts = new(); + + _mockMediator.Send(Arg.Any(), Arg.Any()) + .Returns(callInfo => new ValueTask>(Task.Run(async () => + { + await Task.Delay(100, callInfo.Arg()); + return ErrorOrFactory.From(ThumbnailResponseFixture.CreateThumbnailResponse()); + }, callInfo.Arg()))); + + // Act & Assert + cts.CancelAfter(50); + await Assert.ThrowsAnyAsync(() => _sut.GetThumbnail(path, quality, cts.Token)); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Lumina.Presentation.Api.UnitTests.csproj b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Lumina.Presentation.Api.UnitTests.csproj index c221f0a3..d4d449bf 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Lumina.Presentation.Api.UnitTests.csproj +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Lumina.Presentation.Api.UnitTests.csproj @@ -12,11 +12,13 @@ + +