mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 22:01:10 +00:00
Adds Presentation Api layer unit tests for file system browser dialog
This commit is contained in:
1 parent
7321dc5dab
commit
ce34274fd1
13 files changed
+1697
-9
No files matched your search
+3
-3
@@ -51,7 +51,7 @@ public class DirectoriesController : ApiController
|
||||
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> 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<IEnumerable<FileSystemTreeNodeResponse>> 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<IEnumerable<DirectoryResponse>> 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;
|
||||
|
||||
@@ -48,11 +48,14 @@ public class FilesController : ApiController
|
||||
[FromQuery] bool includeHiddenElements, [EnumeratorCancellation] CancellationToken cancellationToken)
|
||||
{
|
||||
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> 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<IEnumerable<FileResponse>> 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;
|
||||
|
||||
+234
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="DirectoriesController"/> class.
|
||||
/// </summary>
|
||||
[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 =====================================================================================
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DirectoriesControllerTests"/> class.
|
||||
/// </summary>
|
||||
public DirectoriesControllerTests()
|
||||
{
|
||||
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
|
||||
_mockMediator = Substitute.For<ISender>();
|
||||
_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<FileSystemTreeNodeResponse> expectedResponses = _fileSystemTreeNodeResponseFixture.CreateMany(3, 3, 5);
|
||||
_mockMediator.Send(Arg.Any<GetDirectoryTreeQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From(expectedResponses.AsEnumerable()));
|
||||
|
||||
// Act
|
||||
IAsyncEnumerable<FileSystemTreeNodeResponse> result = _sut.GetDirectoryTree(path, includeFiles, includeHiddenElements, cancellationToken);
|
||||
|
||||
// Assert
|
||||
List<FileSystemTreeNodeResponse> 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<GetDirectoryTreeQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Errors.FileManagement.DirectoryNotFound);
|
||||
|
||||
// Act
|
||||
IAsyncEnumerable<FileSystemTreeNodeResponse> result = _sut.GetDirectoryTree(path, includeFiles, includeHiddenElements, cancellationToken);
|
||||
|
||||
// Assert
|
||||
List<FileSystemTreeNodeResponse> 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<FileSystemTreeNodeResponse> expectedResponses = _fileSystemTreeNodeResponseFixture.CreateMany(3, 3, 5);
|
||||
_mockMediator.Send(Arg.Any<GetTreeDirectoriesQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From(expectedResponses.AsEnumerable()));
|
||||
|
||||
// Act
|
||||
IAsyncEnumerable<FileSystemTreeNodeResponse> result = _sut.GetTreeDirectories(path, includeHiddenElements, cancellationToken);
|
||||
|
||||
// Assert
|
||||
List<FileSystemTreeNodeResponse> 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<GetTreeDirectoriesQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Errors.FileManagement.DirectoryNotFound);
|
||||
|
||||
// Act
|
||||
IAsyncEnumerable<FileSystemTreeNodeResponse> result = _sut.GetTreeDirectories(path, includeHiddenElements, cancellationToken);
|
||||
|
||||
// Assert
|
||||
List<FileSystemTreeNodeResponse> 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<DirectoryResponse> expectedResponses = _fixture.CreateMany<DirectoryResponse>(3).ToList();
|
||||
_mockMediator.Send(Arg.Any<GetDirectoriesQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From(expectedResponses.AsEnumerable()));
|
||||
|
||||
// Act
|
||||
IAsyncEnumerable<DirectoryResponse> result = _sut.GetDirectories(path, includeHiddenElements, cancellationToken);
|
||||
|
||||
// Assert
|
||||
List<DirectoryResponse> 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<GetDirectoriesQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Errors.FileManagement.DirectoryNotFound);
|
||||
|
||||
// Act
|
||||
IAsyncEnumerable<DirectoryResponse> result = _sut.GetDirectories(path, includeHiddenElements, cancellationToken);
|
||||
|
||||
// Assert
|
||||
List<DirectoryResponse> 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<FileSystemTreeNodeResponse> expectedResponses = _fileSystemTreeNodeResponseFixture.CreateMany(100, 3, 5);
|
||||
_mockMediator.Send(Arg.Any<GetDirectoryTreeQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From(expectedResponses.AsEnumerable()));
|
||||
|
||||
// Act
|
||||
IAsyncEnumerable<FileSystemTreeNodeResponse> result = _sut.GetDirectoryTree(path, includeFiles, includeHiddenElements, cts.Token);
|
||||
cts.Cancel();
|
||||
|
||||
// Assert
|
||||
List<FileSystemTreeNodeResponse> 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<FileSystemTreeNodeResponse> expectedResponses = _fileSystemTreeNodeResponseFixture.CreateMany(100, 3, 5);
|
||||
_mockMediator.Send(Arg.Any<GetTreeDirectoriesQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From(expectedResponses.AsEnumerable()));
|
||||
|
||||
// Act
|
||||
IAsyncEnumerable<FileSystemTreeNodeResponse> result = _sut.GetTreeDirectories(path, includeHiddenElements, cts.Token);
|
||||
cts.Cancel();
|
||||
|
||||
// Assert
|
||||
List<FileSystemTreeNodeResponse> 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<DirectoryResponse> expectedResponses = _fixture.CreateMany<DirectoryResponse>(100).ToList();
|
||||
_mockMediator.Send(Arg.Any<GetDirectoriesQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From(expectedResponses.AsEnumerable()));
|
||||
|
||||
// Act
|
||||
IAsyncEnumerable<DirectoryResponse> result = _sut.GetDirectories(path, includeHiddenElements, cts.Token);
|
||||
cts.Cancel();
|
||||
|
||||
// Assert
|
||||
List<DirectoryResponse> actualResponses = await result.ToListAsync();
|
||||
actualResponses.Should().BeEmpty();
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
+146
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="DrivesController"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DrivesControllerTests
|
||||
{
|
||||
#region ================================================================== FIELD MEMBERS ================================================================================
|
||||
private readonly ISender _mockMediator;
|
||||
private readonly DrivesController _sut;
|
||||
private readonly FileSystemTreeNodeResponseFixture _fileSystemTreeNodeResponseFixture;
|
||||
#endregion
|
||||
|
||||
#region ====================================================================== CTOR =====================================================================================
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DrivesControllerTests"/> class.
|
||||
/// </summary>
|
||||
public DrivesControllerTests()
|
||||
{
|
||||
_mockMediator = Substitute.For<ISender>();
|
||||
_sut = new DrivesController(_mockMediator);
|
||||
_fileSystemTreeNodeResponseFixture = new FileSystemTreeNodeResponseFixture();
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region ===================================================================== METHODS ===================================================================================
|
||||
[Fact]
|
||||
public async Task GetDrives_WhenCalled_ShouldReturnOkResultWithFileSystemTreeNodeResponses()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
List<FileSystemTreeNodeResponse> expectedResponses = _fileSystemTreeNodeResponseFixture.CreateMany(3, 1, 1);
|
||||
_mockMediator.Send(Arg.Any<GetDrivesQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From(expectedResponses.AsEnumerable()));
|
||||
|
||||
// Act
|
||||
IActionResult result = await _sut.GetDrives(cancellationToken);
|
||||
|
||||
// Assert
|
||||
OkObjectResult okResult = result.Should().BeOfType<OkObjectResult>().Subject;
|
||||
IEnumerable<FileSystemTreeNodeResponse> actualResponses = okResult.Value.Should().BeAssignableTo<IEnumerable<FileSystemTreeNodeResponse>>().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<GetDrivesQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
HttpContext mockHttpContext = Substitute.For<HttpContext>();
|
||||
Dictionary<object, object> mockItems = [];
|
||||
mockHttpContext.Items.Returns(mockItems!);
|
||||
_sut.ControllerContext = new ControllerContext
|
||||
{
|
||||
HttpContext = mockHttpContext
|
||||
};
|
||||
ProblemDetailsFactory mockProblemDetailsFactory = Substitute.For<ProblemDetailsFactory>();
|
||||
mockProblemDetailsFactory.CreateProblemDetails(
|
||||
Arg.Any<HttpContext>(),
|
||||
Arg.Any<int?>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>())
|
||||
.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<ObjectResult>().Subject;
|
||||
objectResult.StatusCode.Should().Be(StatusCodes.Status404NotFound);
|
||||
|
||||
ProblemDetails problemDetails = objectResult.Value.Should().BeOfType<ProblemDetails>().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<Error> { expectedError });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetDrives_WhenCalled_ShouldSendGetDrivesQueryToMediator()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockMediator.Send(Arg.Any<GetDrivesQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From(Enumerable.Empty<FileSystemTreeNodeResponse>()));
|
||||
|
||||
// Act
|
||||
await _sut.GetDrives(cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockMediator.Received(1).Send(Arg.Any<GetDrivesQuery>(), Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetDrives_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
CancellationTokenSource cts = new();
|
||||
|
||||
_mockMediator.Send(Arg.Any<GetDrivesQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => new ValueTask<ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>>(Task.Run(async () =>
|
||||
{
|
||||
await Task.Delay(100, callInfo.Arg<CancellationToken>());
|
||||
return ErrorOrFactory.From(_fileSystemTreeNodeResponseFixture.CreateMany(3, 1, 1).AsEnumerable());
|
||||
}, callInfo.Arg<CancellationToken>())));
|
||||
|
||||
// Act & Assert
|
||||
cts.CancelAfter(50);
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => _sut.GetDrives(cts.Token));
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
+122
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="FileSystemController"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class FileSystemControllerTests
|
||||
{
|
||||
#region ================================================================== FIELD MEMBERS ================================================================================
|
||||
private readonly ISender _mockMediator;
|
||||
private readonly FileSystemController _sut;
|
||||
#endregion
|
||||
|
||||
#region ====================================================================== CTOR =====================================================================================
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="FileSystemControllerTests"/> class.
|
||||
/// </summary>
|
||||
public FileSystemControllerTests()
|
||||
{
|
||||
_mockMediator = Substitute.For<ISender>();
|
||||
_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<GetFileSystemQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedResponse);
|
||||
|
||||
// Act
|
||||
IActionResult result = await _sut.GetType(cancellationToken);
|
||||
|
||||
// Assert
|
||||
OkObjectResult okResult = result.Should().BeOfType<OkObjectResult>().Subject;
|
||||
FileSystemTypeResponse actualResponse = okResult.Value.Should().BeAssignableTo<FileSystemTypeResponse>().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<GetFileSystemQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedResponse);
|
||||
|
||||
// Act
|
||||
IActionResult result = await _sut.GetType(cancellationToken);
|
||||
|
||||
// Assert
|
||||
OkObjectResult okResult = result.Should().BeOfType<OkObjectResult>().Subject;
|
||||
FileSystemTypeResponse actualResponse = okResult.Value.Should().BeAssignableTo<FileSystemTypeResponse>().Subject;
|
||||
actualResponse.PlatformType.Should().Be(platformType);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetType_WhenCalled_ShouldSendGetFileSystemQueryToMediator()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockMediator.Send(Arg.Any<GetFileSystemQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new FileSystemTypeResponse(PlatformType.Windows));
|
||||
|
||||
// Act
|
||||
await _sut.GetType(cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockMediator.Received(1).Send(Arg.Any<GetFileSystemQuery>(), Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetType_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
CancellationTokenSource cts = new();
|
||||
|
||||
_mockMediator.Send(Arg.Any<GetFileSystemQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => new ValueTask<FileSystemTypeResponse>(Task.Run(async () =>
|
||||
{
|
||||
await Task.Delay(100, callInfo.Arg<CancellationToken>());
|
||||
return new FileSystemTypeResponse(PlatformType.Windows);
|
||||
}, callInfo.Arg<CancellationToken>())));
|
||||
|
||||
// Act & Assert
|
||||
cts.CancelAfter(50);
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => _sut.GetType(cts.Token));
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
+171
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="FilesController"/> class.
|
||||
/// </summary>
|
||||
[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 =====================================================================================
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="FilesControllerTests"/> class.
|
||||
/// </summary>
|
||||
public FilesControllerTests()
|
||||
{
|
||||
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
|
||||
_mockMediator = Substitute.For<ISender>();
|
||||
_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<FileSystemTreeNodeResponse> expectedResponses = _fileSystemTreeNodeResponseFixture.CreateMany(3, 3, 5);
|
||||
_mockMediator.Send(Arg.Any<GetTreeFilesQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From(expectedResponses.AsEnumerable()));
|
||||
|
||||
// Act
|
||||
IAsyncEnumerable<FileSystemTreeNodeResponse> result = _sut.GetTreeFiles(path, includeHiddenElements, cancellationToken);
|
||||
|
||||
// Assert
|
||||
List<FileSystemTreeNodeResponse> 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<GetTreeFilesQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Errors.FileManagement.DirectoryNotFound);
|
||||
|
||||
// Act
|
||||
IAsyncEnumerable<FileSystemTreeNodeResponse> result = _sut.GetTreeFiles(path, includeHiddenElements, cancellationToken);
|
||||
|
||||
// Assert
|
||||
List<FileSystemTreeNodeResponse> 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<FileResponse> expectedResponses = _fixture.CreateMany<FileResponse>(3).ToList();
|
||||
_mockMediator.Send(Arg.Any<GetFilesQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From(expectedResponses.AsEnumerable()));
|
||||
|
||||
// Act
|
||||
IAsyncEnumerable<FileResponse> result = _sut.GetFiles(path, includeHiddenElements, cancellationToken);
|
||||
|
||||
// Assert
|
||||
List<FileResponse> 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<GetFilesQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Errors.FileManagement.DirectoryNotFound);
|
||||
|
||||
// Act
|
||||
IAsyncEnumerable<FileResponse> result = _sut.GetFiles(path, includeHiddenElements, cancellationToken);
|
||||
|
||||
// Assert
|
||||
List<FileResponse> 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<FileSystemTreeNodeResponse> expectedResponses = _fileSystemTreeNodeResponseFixture.CreateMany(100, 3, 5);
|
||||
_mockMediator.Send(Arg.Any<GetTreeFilesQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From(expectedResponses.AsEnumerable()));
|
||||
|
||||
// Act
|
||||
IAsyncEnumerable<FileSystemTreeNodeResponse> result = _sut.GetTreeFiles(path, includeHiddenElements, cts.Token);
|
||||
cts.Cancel();
|
||||
|
||||
// Assert
|
||||
List<FileSystemTreeNodeResponse> 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<FileResponse> expectedResponses = _fixture.CreateMany<FileResponse>(100).ToList();
|
||||
_mockMediator.Send(Arg.Any<GetFilesQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From(expectedResponses.AsEnumerable()));
|
||||
|
||||
// Act
|
||||
IAsyncEnumerable<FileResponse> result = _sut.GetFiles(path, includeHiddenElements, cts.Token);
|
||||
cts.Cancel();
|
||||
|
||||
// Assert
|
||||
List<FileResponse> actualResponses = await result.ToListAsync();
|
||||
actualResponses.Should().BeEmpty();
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
+62
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="FileSystemTreeNodeResponse"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class FileSystemTreeNodeResponseFixture
|
||||
{
|
||||
#region ================================================================== FIELD MEMBERS ================================================================================
|
||||
private readonly Faker _faker = new();
|
||||
#endregion
|
||||
|
||||
#region ===================================================================== METHODS ===================================================================================
|
||||
/// <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();
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
+41
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="PathSegmentResponse"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PathSegmentResponseFixture
|
||||
{
|
||||
#region ================================================================== FIELD MEMBERS ================================================================================
|
||||
private readonly Faker _faker = new();
|
||||
#endregion
|
||||
|
||||
#region ===================================================================== METHODS ===================================================================================
|
||||
/// <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();
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
+41
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="PathSeparatorResponse"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PathSeparatorResponseFixture
|
||||
{
|
||||
#region ================================================================== FIELD MEMBERS ================================================================================
|
||||
private readonly Faker _faker = new();
|
||||
#endregion
|
||||
|
||||
#region ===================================================================== METHODS ===================================================================================
|
||||
/// <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();
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
+32
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="ThumbnailResponse"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ThumbnailResponseFixture
|
||||
{
|
||||
#region ===================================================================== METHODS ===================================================================================
|
||||
/// <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));
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
+680
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="PathController"/> class.
|
||||
/// </summary>
|
||||
[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 =====================================================================================
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="PathControllerTests"/> class.
|
||||
/// </summary>
|
||||
public PathControllerTests()
|
||||
{
|
||||
_mockMediator = Substitute.For<ISender>();
|
||||
_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<GetPathRootQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From(expectedResponse));
|
||||
|
||||
// Act
|
||||
IActionResult result = await _sut.GetPathRoot(path, cancellationToken);
|
||||
|
||||
// Assert
|
||||
OkObjectResult okResult = result.Should().BeOfType<OkObjectResult>().Subject;
|
||||
PathSegmentResponse actualResponse = okResult.Value.Should().BeAssignableTo<PathSegmentResponse>().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<GetPathRootQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
_sut.ControllerContext = new ControllerContext();
|
||||
|
||||
ProblemDetailsFactory mockProblemDetailsFactory = Substitute.For<ProblemDetailsFactory>();
|
||||
mockProblemDetailsFactory.CreateProblemDetails(
|
||||
Arg.Any<HttpContext>(),
|
||||
Arg.Any<int?>(),
|
||||
Arg.Is<string>(ErrorType.Validation.ToString()),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>())
|
||||
.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<HttpContext>(),
|
||||
Arg.Any<ModelStateDictionary>(),
|
||||
Arg.Any<int?>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>())
|
||||
.Returns(expectedValidationProblemDetails);
|
||||
|
||||
// Act
|
||||
IActionResult result = await _sut.GetPathRoot(path, cancellationToken);
|
||||
|
||||
// Assert
|
||||
BadRequestObjectResult badRequestResult = result.Should().BeOfType<BadRequestObjectResult>().Subject;
|
||||
badRequestResult.StatusCode.Should().Be(StatusCodes.Status400BadRequest);
|
||||
|
||||
ValidationProblemDetails actualValidationProblemDetails = badRequestResult.Value.Should().BeOfType<ValidationProblemDetails>().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<GetPathRootQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From(_pathSegmentResponseFixture.Create()));
|
||||
|
||||
// Act
|
||||
await _sut.GetPathRoot(path, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockMediator.Received(1).Send(Arg.Is<GetPathRootQuery>(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<GetPathRootQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => new ValueTask<ErrorOr<PathSegmentResponse>>(Task.Run(async () =>
|
||||
{
|
||||
await Task.Delay(100, callInfo.Arg<CancellationToken>());
|
||||
return ErrorOrFactory.From(_pathSegmentResponseFixture.Create());
|
||||
}, callInfo.Arg<CancellationToken>())));
|
||||
|
||||
// Act & Assert
|
||||
cts.CancelAfter(50);
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => _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<GetPathSeparatorQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedResponse);
|
||||
|
||||
// Act
|
||||
IActionResult result = await _sut.GetPathSeparator(cancellationToken);
|
||||
|
||||
// Assert
|
||||
OkObjectResult okResult = result.Should().BeOfType<OkObjectResult>().Subject;
|
||||
PathSeparatorResponse actualResponse = okResult.Value.Should().BeAssignableTo<PathSeparatorResponse>().Subject;
|
||||
actualResponse.Should().BeEquivalentTo(expectedResponse);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPathSeparator_WhenCalled_ShouldSendGetPathSeparatorQueryToMediator()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockMediator.Send(Arg.Any<GetPathSeparatorQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_pathSeparatorResponseFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.GetPathSeparator(cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockMediator.Received(1).Send(Arg.Any<GetPathSeparatorQuery>(), Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPathSeparator_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
CancellationTokenSource cts = new();
|
||||
|
||||
_mockMediator.Send(Arg.Any<GetPathSeparatorQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => new ValueTask<PathSeparatorResponse>(Task.Run(async () =>
|
||||
{
|
||||
await Task.Delay(100, callInfo.Arg<CancellationToken>());
|
||||
return _pathSeparatorResponseFixture.Create();
|
||||
}, callInfo.Arg<CancellationToken>())));
|
||||
|
||||
// Act & Assert
|
||||
cts.CancelAfter(50);
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => _sut.GetPathSeparator(cts.Token));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPathParent_WhenCalled_ShouldReturnOkResultWithPathSegmentResponses()
|
||||
{
|
||||
// Arrange
|
||||
string path = @"C:\Users\TestUser\Documents";
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
IEnumerable<PathSegmentResponse> expectedResponse =
|
||||
[
|
||||
_pathSegmentResponseFixture.Create(),
|
||||
_pathSegmentResponseFixture.Create()
|
||||
];
|
||||
_mockMediator.Send(Arg.Any<GetPathParentQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From(expectedResponse));
|
||||
|
||||
// Act
|
||||
IActionResult result = await _sut.GetPathParent(path, cancellationToken);
|
||||
|
||||
// Assert
|
||||
OkObjectResult okResult = result.Should().BeOfType<OkObjectResult>().Subject;
|
||||
IEnumerable<PathSegmentResponse> actualResponse = okResult.Value.Should().BeAssignableTo<IEnumerable<PathSegmentResponse>>().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<GetPathParentQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
_sut.ControllerContext = new ControllerContext();
|
||||
|
||||
ProblemDetailsFactory mockProblemDetailsFactory = Substitute.For<ProblemDetailsFactory>();
|
||||
mockProblemDetailsFactory.CreateProblemDetails(
|
||||
Arg.Any<HttpContext>(),
|
||||
Arg.Any<int?>(),
|
||||
Arg.Is<string>(ErrorType.Validation.ToString()),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>())
|
||||
.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<HttpContext>(),
|
||||
Arg.Any<ModelStateDictionary>(),
|
||||
Arg.Any<int?>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>())
|
||||
.Returns(expectedValidationProblemDetails);
|
||||
|
||||
// Act
|
||||
IActionResult result = await _sut.GetPathParent(path, cancellationToken);
|
||||
|
||||
// Assert
|
||||
BadRequestObjectResult badRequestResult = result.Should().BeOfType<BadRequestObjectResult>().Subject;
|
||||
badRequestResult.StatusCode.Should().Be(StatusCodes.Status400BadRequest);
|
||||
|
||||
ValidationProblemDetails actualValidationProblemDetails = badRequestResult.Value.Should().BeOfType<ValidationProblemDetails>().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<GetPathParentQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new List<PathSegmentResponse> { _pathSegmentResponseFixture.Create() });
|
||||
|
||||
// Act
|
||||
await _sut.GetPathParent(path, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockMediator.Received(1).Send(Arg.Is<GetPathParentQuery>(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<GetPathParentQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => new ValueTask<ErrorOr<IEnumerable<PathSegmentResponse>>>(Task.Run(async () =>
|
||||
{
|
||||
await Task.Delay(100, callInfo.Arg<CancellationToken>());
|
||||
return ErrorOrFactory.From(new List<PathSegmentResponse>
|
||||
{
|
||||
_pathSegmentResponseFixture.Create()
|
||||
}.AsEnumerable());
|
||||
}, callInfo.Arg<CancellationToken>())));
|
||||
|
||||
// Act & Assert
|
||||
cts.CancelAfter(50);
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => _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<CombinePathCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From(expectedResponse));
|
||||
|
||||
// Act
|
||||
IActionResult result = await _sut.CombinePath(originalPath, newPath, cancellationToken);
|
||||
|
||||
// Assert
|
||||
OkObjectResult okResult = result.Should().BeOfType<OkObjectResult>().Subject;
|
||||
PathSegmentResponse actualResponse = okResult.Value.Should().BeAssignableTo<PathSegmentResponse>().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<CombinePathCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
_sut.ControllerContext = new ControllerContext();
|
||||
|
||||
ProblemDetailsFactory mockProblemDetailsFactory = Substitute.For<ProblemDetailsFactory>();
|
||||
mockProblemDetailsFactory.CreateProblemDetails(
|
||||
Arg.Any<HttpContext>(),
|
||||
Arg.Any<int?>(),
|
||||
Arg.Is<string>(ErrorType.Validation.ToString()),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>())
|
||||
.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<HttpContext>(),
|
||||
Arg.Any<ModelStateDictionary>(),
|
||||
Arg.Any<int?>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>())
|
||||
.Returns(expectedValidationProblemDetails);
|
||||
|
||||
// Act
|
||||
IActionResult result = await _sut.CombinePath(originalPath, newPath, cancellationToken);
|
||||
|
||||
// Assert
|
||||
BadRequestObjectResult badRequestResult = result.Should().BeOfType<BadRequestObjectResult>().Subject;
|
||||
badRequestResult.StatusCode.Should().Be(StatusCodes.Status400BadRequest);
|
||||
|
||||
ValidationProblemDetails actualValidationProblemDetails = badRequestResult.Value.Should().BeOfType<ValidationProblemDetails>().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<CombinePathCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From(_pathSegmentResponseFixture.Create()));
|
||||
|
||||
// Act
|
||||
await _sut.CombinePath(originalPath, newPath, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockMediator.Received(1).Send(Arg.Is<CombinePathCommand>(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<CombinePathCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => new ValueTask<ErrorOr<PathSegmentResponse>>(Task.Run(async () =>
|
||||
{
|
||||
await Task.Delay(100, callInfo.Arg<CancellationToken>());
|
||||
return ErrorOrFactory.From(_pathSegmentResponseFixture.Create());
|
||||
}, callInfo.Arg<CancellationToken>())));
|
||||
|
||||
// Act & Assert
|
||||
cts.CancelAfter(50);
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => _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<PathSegmentResponse> expectedResponse =
|
||||
[
|
||||
_pathSegmentResponseFixture.Create(),
|
||||
_pathSegmentResponseFixture.Create(),
|
||||
_pathSegmentResponseFixture.Create()
|
||||
];
|
||||
_mockMediator.Send(Arg.Any<SplitPathCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From(expectedResponse));
|
||||
|
||||
// Act
|
||||
IActionResult result = await _sut.SplitPath(path, cancellationToken);
|
||||
|
||||
// Assert
|
||||
OkObjectResult okResult = result.Should().BeOfType<OkObjectResult>().Subject;
|
||||
IEnumerable<PathSegmentResponse> actualResponse = okResult.Value.Should().BeAssignableTo<IEnumerable<PathSegmentResponse>>().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<SplitPathCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
_sut.ControllerContext = new ControllerContext();
|
||||
|
||||
ProblemDetailsFactory mockProblemDetailsFactory = Substitute.For<ProblemDetailsFactory>();
|
||||
mockProblemDetailsFactory.CreateProblemDetails(
|
||||
Arg.Any<HttpContext>(),
|
||||
Arg.Any<int?>(),
|
||||
Arg.Is<string>(ErrorType.Validation.ToString()),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>())
|
||||
.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<HttpContext>(),
|
||||
Arg.Any<ModelStateDictionary>(),
|
||||
Arg.Any<int?>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>())
|
||||
.Returns(expectedValidationProblemDetails);
|
||||
|
||||
// Act
|
||||
IActionResult result = await _sut.SplitPath(path, cancellationToken);
|
||||
|
||||
// Assert
|
||||
BadRequestObjectResult badRequestResult = result.Should().BeOfType<BadRequestObjectResult>().Subject;
|
||||
badRequestResult.StatusCode.Should().Be(StatusCodes.Status400BadRequest);
|
||||
|
||||
ValidationProblemDetails actualValidationProblemDetails = badRequestResult.Value.Should().BeOfType<ValidationProblemDetails>().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<SplitPathCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new List<PathSegmentResponse> { _pathSegmentResponseFixture.Create() });
|
||||
|
||||
// Act
|
||||
await _sut.SplitPath(path, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockMediator.Received(1).Send(Arg.Is<SplitPathCommand>(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<SplitPathCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => new ValueTask<ErrorOr<IEnumerable<PathSegmentResponse>>>(Task.Run(async () =>
|
||||
{
|
||||
await Task.Delay(100, callInfo.Arg<CancellationToken>());
|
||||
return ErrorOrFactory.From(new List<PathSegmentResponse>
|
||||
{
|
||||
_pathSegmentResponseFixture.Create()
|
||||
}.AsEnumerable());
|
||||
}, callInfo.Arg<CancellationToken>())));
|
||||
|
||||
// Act & Assert
|
||||
cts.CancelAfter(50);
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => _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<ValidatePathQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedResponse);
|
||||
|
||||
// Act
|
||||
IActionResult result = await _sut.ValidatePath(path, cancellationToken);
|
||||
|
||||
// Assert
|
||||
OkObjectResult okResult = result.Should().BeOfType<OkObjectResult>().Subject;
|
||||
PathValidResponse actualResponse = okResult.Value.Should().BeAssignableTo<PathValidResponse>().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<ValidatePathQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new PathValidResponse(true));
|
||||
|
||||
// Act
|
||||
await _sut.ValidatePath(path, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockMediator.Received(1).Send(Arg.Is<ValidatePathQuery>(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<ValidatePathQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => new ValueTask<PathValidResponse>(Task.Run(async () =>
|
||||
{
|
||||
await Task.Delay(100, callInfo.Arg<CancellationToken>());
|
||||
return new PathValidResponse(true);
|
||||
}, callInfo.Arg<CancellationToken>())));
|
||||
|
||||
// Act & Assert
|
||||
cts.CancelAfter(50);
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => _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<CheckPathExistsQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedResponse);
|
||||
|
||||
// Act
|
||||
IActionResult result = await _sut.CheckPathExists(path, cancellationToken);
|
||||
|
||||
// Assert
|
||||
OkObjectResult okResult = result.Should().BeOfType<OkObjectResult>().Subject;
|
||||
PathExistsResponse actualResponse = okResult.Value.Should().BeAssignableTo<PathExistsResponse>().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<CheckPathExistsQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new PathExistsResponse(true));
|
||||
|
||||
// Act
|
||||
await _sut.CheckPathExists(path, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockMediator.Received(1).Send(Arg.Is<CheckPathExistsQuery>(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<CheckPathExistsQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => new ValueTask<PathExistsResponse>(Task.Run(async () =>
|
||||
{
|
||||
await Task.Delay(100, callInfo.Arg<CancellationToken>());
|
||||
return new PathExistsResponse(true);
|
||||
}, callInfo.Arg<CancellationToken>())));
|
||||
|
||||
// Act & Assert
|
||||
cts.CancelAfter(50);
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => _sut.CheckPathExists(path, cts.Token));
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
+154
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ThumbnailsController"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ThumbnailsControllerTests
|
||||
{
|
||||
#region ================================================================== FIELD MEMBERS ================================================================================
|
||||
private readonly ISender _mockMediator;
|
||||
private readonly ThumbnailsController _sut;
|
||||
#endregion
|
||||
|
||||
#region ====================================================================== CTOR =====================================================================================
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ThumbnailsControllerTests"/> class.
|
||||
/// </summary>
|
||||
public ThumbnailsControllerTests()
|
||||
{
|
||||
_mockMediator = Substitute.For<ISender>();
|
||||
_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<GetThumbnailQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From(expectedResponse));
|
||||
|
||||
// Act
|
||||
IActionResult result = await _sut.GetThumbnail(path, quality, cancellationToken);
|
||||
|
||||
// Assert
|
||||
FileContentResult fileResult = result.Should().BeOfType<FileContentResult>().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<GetThumbnailQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
HttpContext mockHttpContext = Substitute.For<HttpContext>();
|
||||
Dictionary<object, object> mockItems = [];
|
||||
mockHttpContext.Items.Returns(mockItems!);
|
||||
_sut.ControllerContext = new ControllerContext
|
||||
{
|
||||
HttpContext = mockHttpContext
|
||||
};
|
||||
ProblemDetailsFactory mockProblemDetailsFactory = Substitute.For<ProblemDetailsFactory>();
|
||||
mockProblemDetailsFactory.CreateProblemDetails(
|
||||
Arg.Any<HttpContext>(),
|
||||
Arg.Any<int?>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>())
|
||||
.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<ObjectResult>().Subject;
|
||||
objectResult.StatusCode.Should().Be(StatusCodes.Status404NotFound);
|
||||
|
||||
ProblemDetails problemDetails = objectResult.Value.Should().BeOfType<ProblemDetails>().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<Error> { 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<GetThumbnailQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From(ThumbnailResponseFixture.CreateThumbnailResponse()));
|
||||
|
||||
// Act
|
||||
await _sut.GetThumbnail(path, quality, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockMediator.Received(1).Send(Arg.Is<GetThumbnailQuery>(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<GetThumbnailQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => new ValueTask<ErrorOr<ThumbnailResponse>>(Task.Run(async () =>
|
||||
{
|
||||
await Task.Delay(100, callInfo.Arg<CancellationToken>());
|
||||
return ErrorOrFactory.From(ThumbnailResponseFixture.CreateThumbnailResponse());
|
||||
}, callInfo.Arg<CancellationToken>())));
|
||||
|
||||
// Act & Assert
|
||||
cts.CancelAfter(50);
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => _sut.GetThumbnail(path, quality, cts.Token));
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
+2
@@ -12,11 +12,13 @@
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AutoFixture.AutoNSubstitute" Version="4.18.1" />
|
||||
<PackageReference Include="AutoFixture.Xunit2" Version="4.18.1" />
|
||||
<PackageReference Include="Bogus" Version="35.6.0" />
|
||||
<PackageReference Include="coverlet.collector" Version="6.0.0" />
|
||||
<PackageReference Include="FluentAssertions" Version="6.12.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
|
||||
<PackageReference Include="NSubstitute" Version="5.1.0" />
|
||||
<PackageReference Include="System.Linq.Async" Version="6.0.1" />
|
||||
<PackageReference Include="xunit" Version="2.5.3" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.3" />
|
||||
</ItemGroup>
|
||||
|
||||
Reference in new issue
Block a user