mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-02 22:11:10 +00:00
Replaces MVC with FastEndpoints in Lumina.Presentation.Api
This commit is contained in:
1 parent
b1a20716df
commit
c7b8bc2f1c
519 files changed
+15329
-8539
No files matched your search
-278
@@ -1,278 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using FluentAssertions;
|
||||
using Lumina.Presentation.Api.Common.Http;
|
||||
using Lumina.Presentation.Api.Core.Controllers.Common;
|
||||
using Lumina.Presentation.Api.UnitTests.Core.Controllers.Common.Fixtures;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Infrastructure;
|
||||
using Microsoft.AspNetCore.Mvc.ModelBinding;
|
||||
using NSubstitute;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.UnitTests.Core.Controllers.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ApiController"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ApiControllerTests
|
||||
{
|
||||
private readonly ApiControllerFixture _sut;
|
||||
private readonly HttpContext _mockHttpContext;
|
||||
private readonly ProblemDetailsFactory _mockProblemDetailsFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ApiControllerTests"/> class.
|
||||
/// </summary>
|
||||
public ApiControllerTests()
|
||||
{
|
||||
_sut = new ApiControllerFixture();
|
||||
_mockHttpContext = Substitute.For<HttpContext>();
|
||||
_mockProblemDetailsFactory = Substitute.For<ProblemDetailsFactory>();
|
||||
_sut.ControllerContext = new ControllerContext
|
||||
{
|
||||
HttpContext = _mockHttpContext
|
||||
};
|
||||
_sut.ProblemDetailsFactory = _mockProblemDetailsFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Problem_WhenCalledWithNoErrors_ShouldReturnGenericProblem()
|
||||
{
|
||||
// Arrange
|
||||
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());
|
||||
|
||||
_sut.ProblemDetailsFactory = mockProblemDetailsFactory;
|
||||
|
||||
// Act
|
||||
IActionResult result = _sut.TestProblem([]);
|
||||
|
||||
// Assert
|
||||
result.Should().BeOfType<ObjectResult>();
|
||||
ObjectResult objectResult = (ObjectResult)result;
|
||||
objectResult.Value.Should().BeOfType<ProblemDetails>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Problem_WhenCalledWithValidationErrors_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
List<Error> errors = [
|
||||
Error.Validation("Code1", "Description1"),
|
||||
Error.Validation("Code2", "Description2")
|
||||
];
|
||||
|
||||
_mockProblemDetailsFactory.CreateValidationProblemDetails(
|
||||
Arg.Any<HttpContext>(),
|
||||
Arg.Any<ModelStateDictionary>(),
|
||||
Arg.Any<int?>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>())
|
||||
.Returns(new ValidationProblemDetails());
|
||||
|
||||
// Act
|
||||
IActionResult result = _sut.TestProblem(errors);
|
||||
|
||||
// Assert
|
||||
result.Should().BeOfType<ObjectResult>();
|
||||
ObjectResult objectResult = (ObjectResult)result;
|
||||
objectResult.Value.Should().BeOfType<ValidationProblemDetails>();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(ErrorType.Conflict, StatusCodes.Status409Conflict)]
|
||||
[InlineData(ErrorType.NotFound, StatusCodes.Status404NotFound)]
|
||||
[InlineData(ErrorType.Validation, StatusCodes.Status400BadRequest)]
|
||||
[InlineData(ErrorType.Failure, StatusCodes.Status403Forbidden)]
|
||||
[InlineData(ErrorType.Unexpected, StatusCodes.Status500InternalServerError)]
|
||||
public void Problem_WhenCalledWithSingleError_ShouldReturnCorrectStatusCode(ErrorType errorType, int expectedStatusCode)
|
||||
{
|
||||
// Arrange
|
||||
Error error = errorType switch
|
||||
{
|
||||
ErrorType.Conflict => Error.Conflict("ErrorCode", "ErrorDescription"),
|
||||
ErrorType.NotFound => Error.NotFound("ErrorCode", "ErrorDescription"),
|
||||
ErrorType.Validation => Error.Validation("ErrorCode", "ErrorDescription"),
|
||||
ErrorType.Failure => Error.Failure("ErrorCode", "ErrorDescription"),
|
||||
_ => Error.Unexpected("ErrorCode", "ErrorDescription"),
|
||||
};
|
||||
List<Error> errors = [error];
|
||||
|
||||
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 = expectedStatusCode });
|
||||
|
||||
mockProblemDetailsFactory.CreateValidationProblemDetails(
|
||||
Arg.Any<HttpContext>(),
|
||||
Arg.Any<ModelStateDictionary>(),
|
||||
Arg.Any<int?>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>())
|
||||
.Returns(new ValidationProblemDetails { Status = expectedStatusCode });
|
||||
|
||||
_sut.ProblemDetailsFactory = mockProblemDetailsFactory;
|
||||
|
||||
// Act
|
||||
IActionResult result = _sut.TestProblem(errors);
|
||||
|
||||
// Assert
|
||||
if (errorType == ErrorType.Validation)
|
||||
{
|
||||
result.Should().BeOfType<BadRequestObjectResult>();
|
||||
BadRequestObjectResult badRequestResult = (BadRequestObjectResult)result;
|
||||
badRequestResult.StatusCode.Should().Be(expectedStatusCode);
|
||||
badRequestResult.Value.Should().BeOfType<ValidationProblemDetails>();
|
||||
((ValidationProblemDetails)badRequestResult.Value!).Status.Should().Be(expectedStatusCode);
|
||||
|
||||
mockProblemDetailsFactory.Received(1).CreateValidationProblemDetails(
|
||||
Arg.Any<HttpContext>(),
|
||||
Arg.Any<ModelStateDictionary>(),
|
||||
Arg.Is<int?>(status => status == null),
|
||||
Arg.Is<string>(title => title == "One or more validation errors occurred."),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>());
|
||||
}
|
||||
else
|
||||
{
|
||||
result.Should().BeOfType<ObjectResult>();
|
||||
ObjectResult objectResult = (ObjectResult)result;
|
||||
objectResult.StatusCode.Should().Be(expectedStatusCode);
|
||||
objectResult.Value.Should().BeOfType<ProblemDetails>();
|
||||
((ProblemDetails)objectResult.Value!).Status.Should().Be(expectedStatusCode);
|
||||
|
||||
mockProblemDetailsFactory.Received(1).CreateProblemDetails(
|
||||
Arg.Any<HttpContext>(),
|
||||
Arg.Is<int?>(status => status == expectedStatusCode),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>());
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Problem_WhenCalledWithMixedErrors_ShouldReturnBadRequestObjectResult()
|
||||
{
|
||||
// Arrange
|
||||
List<Error> errors = [
|
||||
Error.Validation("ValidationCode", "Validation Error"),
|
||||
Error.Failure("FailureCode", "Failure Error")
|
||||
];
|
||||
|
||||
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.Status400BadRequest });
|
||||
|
||||
_sut.ProblemDetailsFactory = mockProblemDetailsFactory;
|
||||
|
||||
// Act
|
||||
IActionResult result = _sut.TestProblem(errors);
|
||||
|
||||
// Assert
|
||||
result.Should().BeOfType<ObjectResult>();
|
||||
ObjectResult objectResult = (ObjectResult)result;
|
||||
objectResult.StatusCode.Should().Be(StatusCodes.Status400BadRequest);
|
||||
objectResult.Value.Should().BeOfType<ProblemDetails>();
|
||||
((ProblemDetails)objectResult.Value!).Status.Should().Be(StatusCodes.Status400BadRequest);
|
||||
|
||||
mockProblemDetailsFactory.Received(1).CreateProblemDetails(
|
||||
Arg.Any<HttpContext>(),
|
||||
Arg.Is<int?>(status => status == StatusCodes.Status400BadRequest),
|
||||
Arg.Is<string>(title => title == "Validation"),
|
||||
Arg.Any<string>(),
|
||||
Arg.Is<string>(detail => detail == "Validation Error"),
|
||||
Arg.Any<string>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Problem_WhenCalled_ShouldAddErrorsToHttpContext()
|
||||
{
|
||||
// Arrange
|
||||
List<Error> errors = [Error.Failure("ErrorCode", "ErrorDescription")];
|
||||
Dictionary<object, object> mockItems = [];
|
||||
_mockHttpContext.Items.Returns(mockItems!);
|
||||
|
||||
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());
|
||||
|
||||
_sut.ProblemDetailsFactory = mockProblemDetailsFactory;
|
||||
|
||||
// Act
|
||||
_sut.TestProblem(errors);
|
||||
|
||||
// Assert
|
||||
mockItems.Should().ContainKey(HttpContextItemKeys.ERRORS);
|
||||
mockItems[HttpContextItemKeys.ERRORS].Should().BeEquivalentTo(errors);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ValidationProblem_WhenCalled_ShouldAddErrorsToModelState()
|
||||
{
|
||||
// Arrange
|
||||
List<Error> errors = [
|
||||
Error.Validation("Code1", "Description1"),
|
||||
Error.Validation("Code2", "Description2")
|
||||
];
|
||||
|
||||
_mockProblemDetailsFactory.CreateValidationProblemDetails(
|
||||
Arg.Any<HttpContext>(),
|
||||
Arg.Any<ModelStateDictionary>(),
|
||||
Arg.Any<int?>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>())
|
||||
.Returns(callInfo =>
|
||||
{
|
||||
ModelStateDictionary modelState = callInfo.ArgAt<ModelStateDictionary>(1);
|
||||
return new ValidationProblemDetails(modelState);
|
||||
});
|
||||
|
||||
// Act
|
||||
IActionResult result = _sut.TestValidationProblem(errors);
|
||||
|
||||
// Assert
|
||||
result.Should().BeOfType<ObjectResult>();
|
||||
ObjectResult objectResult = (ObjectResult)result;
|
||||
ValidationProblemDetails validationProblem = objectResult.Value.Should().BeOfType<ValidationProblemDetails>().Subject;
|
||||
validationProblem.Errors.Should().ContainKeys("Code1", "Code2");
|
||||
validationProblem.Errors["Code1"].Should().Contain("Description1");
|
||||
validationProblem.Errors["Code2"].Should().Contain("Description2");
|
||||
}
|
||||
}
|
||||
-36
@@ -1,36 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Presentation.Api.Core.Controllers.Common;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.UnitTests.Core.Controllers.Common.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="ApiController"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ApiControllerFixture : ApiController
|
||||
{
|
||||
/// <summary>
|
||||
/// Returns a standardized error response using the <see cref="ProblemDetails"/> format.
|
||||
/// </summary>
|
||||
/// <param name="errors">A list of errors to include in the response.</param>
|
||||
/// <returns>An <see cref="IActionResult"/> with the problem details containing the specified errors.</returns>
|
||||
public IActionResult TestProblem(List<Error> errors)
|
||||
{
|
||||
return Problem(errors);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns a standardized validation error response using the <see cref="ValidationProblemDetails"/> format.
|
||||
/// </summary>
|
||||
/// <param name="errors">A list of validation errors to include in the response.</param>
|
||||
/// <returns>An <see cref="IActionResult"/> with the validation problem details containing the specified errors.</returns>
|
||||
public IActionResult TestValidationProblem(List<Error> errors)
|
||||
{
|
||||
return ValidationProblem(errors);
|
||||
}
|
||||
}
|
||||
-228
@@ -1,228 +0,0 @@
|
||||
#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
|
||||
{
|
||||
private readonly IFixture _fixture;
|
||||
private readonly ISender _mockMediator;
|
||||
private readonly DirectoriesController _sut;
|
||||
private readonly FileSystemTreeNodeResponseFixture _fileSystemTreeNodeResponseFixture;
|
||||
|
||||
/// <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();
|
||||
}
|
||||
|
||||
[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();
|
||||
}
|
||||
}
|
||||
-149
@@ -1,149 +0,0 @@
|
||||
#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
|
||||
{
|
||||
private readonly ISender _mockMediator;
|
||||
private readonly DrivesController _sut;
|
||||
private readonly FileSystemTreeNodeResponseFixture _fileSystemTreeNodeResponseFixture;
|
||||
|
||||
/// <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();
|
||||
}
|
||||
|
||||
[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();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockMediator.Send(Arg.Any<GetDrivesQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => new ValueTask<ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>>(Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return ErrorOrFactory.From(_fileSystemTreeNodeResponseFixture.CreateMany(3, 1, 1).AsEnumerable());
|
||||
}, callInfo.Arg<CancellationToken>())));
|
||||
|
||||
// Act
|
||||
Task<IActionResult> operationTask = _sut.GetDrives(cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
}
|
||||
-115
@@ -1,115 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Core.FileManagement.FileSystem.Queries.GetFileSystem;
|
||||
using Lumina.Contracts.Enums.FileSystem;
|
||||
using Lumina.Contracts.Responses.FileManagement;
|
||||
using Lumina.Presentation.Api.Core.Controllers.FileManagement;
|
||||
using Mediator;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
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
|
||||
{
|
||||
private readonly ISender _mockMediator;
|
||||
private readonly FileSystemController _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="FileSystemControllerTests"/> class.
|
||||
/// </summary>
|
||||
public FileSystemControllerTests()
|
||||
{
|
||||
_mockMediator = Substitute.For<ISender>();
|
||||
_sut = new FileSystemController(_mockMediator);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetType_WhenCalled_ShouldReturnOkResultWithFileSystemTypeResponse()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
FileSystemTypeResponse expectedResponse = new(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(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();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockMediator.Send(Arg.Any<GetFileSystemQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => new ValueTask<FileSystemTypeResponse>(Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return new FileSystemTypeResponse(PlatformType.Windows);
|
||||
}, callInfo.Arg<CancellationToken>())));
|
||||
|
||||
// Act
|
||||
Task<IActionResult> operationTask = _sut.GetType(cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
}
|
||||
-165
@@ -1,165 +0,0 @@
|
||||
#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
|
||||
{
|
||||
private readonly IFixture _fixture;
|
||||
private readonly ISender _mockMediator;
|
||||
private readonly FilesController _sut;
|
||||
private readonly FileSystemTreeNodeResponseFixture _fileSystemTreeNodeResponseFixture;
|
||||
|
||||
/// <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();
|
||||
}
|
||||
|
||||
[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();
|
||||
}
|
||||
}
|
||||
-737
@@ -1,737 +0,0 @@
|
||||
#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
|
||||
{
|
||||
private readonly ISender _mockMediator;
|
||||
private readonly PathController _sut;
|
||||
private readonly PathSegmentResponseFixture _pathSegmentResponseFixture;
|
||||
private readonly PathSeparatorResponseFixture _pathSeparatorResponseFixture;
|
||||
|
||||
/// <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();
|
||||
}
|
||||
|
||||
[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();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockMediator.Send(Arg.Any<GetPathRootQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => new ValueTask<ErrorOr<PathSegmentResponse>>(Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return ErrorOrFactory.From(_pathSegmentResponseFixture.Create());
|
||||
}, callInfo.Arg<CancellationToken>())));
|
||||
|
||||
// Act
|
||||
Task<IActionResult> operationTask = _sut.GetPathRoot(path, cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
|
||||
[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();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockMediator.Send(Arg.Any<GetPathSeparatorQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => new ValueTask<PathSeparatorResponse>(Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return _pathSeparatorResponseFixture.Create();
|
||||
}, callInfo.Arg<CancellationToken>())));
|
||||
|
||||
// Act
|
||||
Task<IActionResult> operationTask = _sut.GetPathSeparator(cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
|
||||
[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();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockMediator.Send(Arg.Any<GetPathParentQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => new ValueTask<ErrorOr<IEnumerable<PathSegmentResponse>>>(Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return ErrorOrFactory.From(new List<PathSegmentResponse>
|
||||
{
|
||||
_pathSegmentResponseFixture.Create()
|
||||
}.AsEnumerable());
|
||||
}, callInfo.Arg<CancellationToken>())));
|
||||
|
||||
// Act
|
||||
Task<IActionResult> operationTask = _sut.GetPathParent(path, cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
|
||||
[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();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockMediator.Send(Arg.Any<CombinePathCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => new ValueTask<ErrorOr<PathSegmentResponse>>(Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return ErrorOrFactory.From(_pathSegmentResponseFixture.Create());
|
||||
}, callInfo.Arg<CancellationToken>())));
|
||||
|
||||
// Act
|
||||
Task<IActionResult> operationTask = _sut.CombinePath(originalPath, newPath, cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
|
||||
[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();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockMediator.Send(Arg.Any<SplitPathCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => new ValueTask<ErrorOr<IEnumerable<PathSegmentResponse>>>(Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return ErrorOrFactory.From(new List<PathSegmentResponse>
|
||||
{
|
||||
_pathSegmentResponseFixture.Create()
|
||||
}.AsEnumerable());
|
||||
}, callInfo.Arg<CancellationToken>())));
|
||||
|
||||
// Act
|
||||
Task<IActionResult> operationTask = _sut.SplitPath(path, cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
|
||||
[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();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockMediator.Send(Arg.Any<ValidatePathQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => new ValueTask<PathValidResponse>(Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return new PathValidResponse(true);
|
||||
}, callInfo.Arg<CancellationToken>())));
|
||||
|
||||
// Act
|
||||
Task<IActionResult> operationTask = _sut.ValidatePath(path, cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
|
||||
[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, true, 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, true, 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();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockMediator.Send(Arg.Any<CheckPathExistsQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => new ValueTask<PathExistsResponse>(Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return new PathExistsResponse(true);
|
||||
}, callInfo.Arg<CancellationToken>())));
|
||||
|
||||
// Act
|
||||
Task<IActionResult> operationTask = _sut.CheckPathExists(path, true, cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
}
|
||||
-157
@@ -1,157 +0,0 @@
|
||||
#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
|
||||
{
|
||||
private readonly ISender _mockMediator;
|
||||
private readonly ThumbnailsController _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ThumbnailsControllerTests"/> class.
|
||||
/// </summary>
|
||||
public ThumbnailsControllerTests()
|
||||
{
|
||||
_mockMediator = Substitute.For<ISender>();
|
||||
_sut = new ThumbnailsController(_mockMediator);
|
||||
}
|
||||
|
||||
[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();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockMediator.Send(Arg.Any<GetThumbnailQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => new ValueTask<ErrorOr<ThumbnailResponse>>(Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return ErrorOrFactory.From(ThumbnailResponseFixture.CreateThumbnailResponse());
|
||||
}, callInfo.Arg<CancellationToken>())));
|
||||
|
||||
// Act
|
||||
Task<IActionResult> operationTask = _sut.GetThumbnail(path, quality, cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
}
|
||||
+191
@@ -0,0 +1,191 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using FastEndpoints;
|
||||
using FluentAssertions;
|
||||
using Lumina.Presentation.Api.UnitTests.Core.Endpoints.Common.Fixtures;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="BaseEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class BaseEndpointTests
|
||||
{
|
||||
private readonly BaseEndpointFixture _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="BaseEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public BaseEndpointTests()
|
||||
{
|
||||
_sut = Factory.Create<BaseEndpointFixture>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Problem_WhenCalledWithNoErrors_ShouldReturnGenericProblem()
|
||||
{
|
||||
// Act
|
||||
IResult result = _sut.TestProblem([]);
|
||||
|
||||
// Assert
|
||||
result.Should().BeOfType<ProblemHttpResult>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Problem_WhenCalledWithValidationErrors_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
List<Error> errors = [
|
||||
Error.Validation("Code1", "Description1"),
|
||||
Error.Validation("Code2", "Description2")
|
||||
];
|
||||
|
||||
// Act
|
||||
IResult result = _sut.TestProblem(errors);
|
||||
|
||||
// Assert
|
||||
result.Should().BeOfType<ProblemHttpResult>();
|
||||
ProblemHttpResult problemDetails = (ProblemHttpResult)result;
|
||||
problemDetails.StatusCode.Should().Be(StatusCodes.Status422UnprocessableEntity);
|
||||
problemDetails.ContentType.Should().Be("application/problem+json");
|
||||
problemDetails.ProblemDetails.Should().BeOfType<HttpValidationProblemDetails>();
|
||||
HttpValidationProblemDetails validationProblemDetails = (HttpValidationProblemDetails)problemDetails.ProblemDetails;
|
||||
validationProblemDetails.Status.Should().Be(StatusCodes.Status422UnprocessableEntity);
|
||||
validationProblemDetails.Title.Should().Be("Validation Error");
|
||||
validationProblemDetails.Detail.Should().Be("One or more validation errors occurred.");
|
||||
validationProblemDetails.Type.Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2");
|
||||
validationProblemDetails.Errors.Should().HaveCount(2);
|
||||
validationProblemDetails.Errors["Code1"].Should().BeEquivalentTo(["Description1"]);
|
||||
validationProblemDetails.Errors["Code2"].Should().BeEquivalentTo(["Description2"]);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(ErrorType.Conflict, StatusCodes.Status409Conflict)]
|
||||
[InlineData(ErrorType.NotFound, StatusCodes.Status404NotFound)]
|
||||
[InlineData(ErrorType.Failure, StatusCodes.Status403Forbidden)]
|
||||
[InlineData(ErrorType.Unexpected, StatusCodes.Status500InternalServerError)]
|
||||
public void Problem_WhenCalledWithSingleError_ShouldReturnCorrectStatusCode(ErrorType errorType, int expectedStatusCode)
|
||||
{
|
||||
// Arrange
|
||||
Error error = errorType switch
|
||||
{
|
||||
ErrorType.Conflict => Error.Conflict("ErrorCode", "ErrorDescription"),
|
||||
ErrorType.NotFound => Error.NotFound("ErrorCode", "ErrorDescription"),
|
||||
ErrorType.Validation => Error.Validation("ErrorCode", "ErrorDescription"),
|
||||
ErrorType.Failure => Error.Failure("ErrorCode", "ErrorDescription"),
|
||||
_ => Error.Unexpected("ErrorCode", "ErrorDescription"),
|
||||
};
|
||||
List<Error> errors = [error];
|
||||
|
||||
// Act
|
||||
IResult result = _sut.TestProblem(errors);
|
||||
|
||||
// Assert
|
||||
result.Should().BeOfType<ProblemHttpResult>();
|
||||
ProblemHttpResult problemResult = (ProblemHttpResult)result;
|
||||
problemResult.StatusCode.Should().Be(expectedStatusCode);
|
||||
problemResult.ProblemDetails.Status.Should().Be(expectedStatusCode);
|
||||
problemResult.ProblemDetails.Title.Should().Be("ErrorCode");
|
||||
problemResult.ProblemDetails.Detail.Should().Be("ErrorDescription");
|
||||
problemResult.ProblemDetails.Instance.Should().NotBeNull();
|
||||
problemResult.ProblemDetails.Extensions.Should().ContainKey("traceId");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Problem_WhenCalledWithSingleValidationError_ShouldReturnCorrectStatusCode()
|
||||
{
|
||||
// Arrange
|
||||
Error error = Error.Validation();
|
||||
List<Error> errors = [error];
|
||||
|
||||
// Act
|
||||
IResult result = _sut.TestProblem(errors);
|
||||
|
||||
// Assert
|
||||
result.Should().BeOfType<ProblemHttpResult>();
|
||||
ProblemHttpResult problemResult = (ProblemHttpResult)result;
|
||||
problemResult.StatusCode.Should().Be(422);
|
||||
problemResult.ProblemDetails.Status.Should().Be(StatusCodes.Status422UnprocessableEntity);
|
||||
problemResult.ProblemDetails.Title.Should().Be("Validation Error");
|
||||
problemResult.ProblemDetails.Detail.Should().Be("One or more validation errors occurred.");
|
||||
problemResult.ProblemDetails.Instance.Should().NotBeNull();
|
||||
problemResult.ProblemDetails.Extensions.Should().ContainKey("traceId");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Problem_WhenCalledWithMixedErrors_ShouldReturnProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
List<Error> errors = [
|
||||
Error.NotFound("FailureCode", "Failure Error"),
|
||||
Error.Failure("FailureCode", "Failure Error")
|
||||
];
|
||||
|
||||
// Act
|
||||
IResult result = _sut.TestProblem(errors);
|
||||
|
||||
// Assert
|
||||
result.Should().BeOfType<ProblemHttpResult>();
|
||||
ProblemHttpResult problemResult = (ProblemHttpResult)result;
|
||||
problemResult.StatusCode.Should().BeOneOf(StatusCodes.Status404NotFound, StatusCodes.Status400BadRequest);
|
||||
problemResult.ProblemDetails.Status.Should().BeOneOf(StatusCodes.Status404NotFound, StatusCodes.Status400BadRequest);
|
||||
problemResult.ProblemDetails.Title.Should().Be("FailureCode");
|
||||
problemResult.ProblemDetails.Detail.Should().Be("Failure Error");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ValidationProblem_WhenCalled_ShouldReturnValidationProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
List<Error> errors = [
|
||||
Error.Validation("Code1", "Description1"),
|
||||
Error.Validation("Code2", "Description2")
|
||||
];
|
||||
|
||||
// Act
|
||||
IResult result = _sut.TestValidationProblem(errors);
|
||||
|
||||
// Assert
|
||||
result.Should().BeOfType<ProblemHttpResult>();
|
||||
ProblemHttpResult problemDetails = (ProblemHttpResult)result;
|
||||
problemDetails.StatusCode.Should().Be(StatusCodes.Status422UnprocessableEntity);
|
||||
problemDetails.ContentType.Should().Be("application/problem+json");
|
||||
problemDetails.ProblemDetails.Should().BeOfType<HttpValidationProblemDetails>();
|
||||
HttpValidationProblemDetails validationProblemDetails = (HttpValidationProblemDetails)problemDetails.ProblemDetails;
|
||||
validationProblemDetails.Status.Should().Be(StatusCodes.Status422UnprocessableEntity);
|
||||
validationProblemDetails.Title.Should().Be("Validation Error");
|
||||
validationProblemDetails.Detail.Should().Be("One or more validation errors occurred.");
|
||||
validationProblemDetails.Type.Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2");
|
||||
validationProblemDetails.Errors.Should().HaveCount(2);
|
||||
validationProblemDetails.Errors["Code1"].Should().BeEquivalentTo(["Description1"]);
|
||||
validationProblemDetails.Errors["Code2"].Should().BeEquivalentTo(["Description2"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ValidationProblem_WhenCalledWithDuplicateErrorCodes_ShouldMergeDescriptions()
|
||||
{
|
||||
// Arrange
|
||||
List<Error> errors = [
|
||||
Error.Validation("Code1", "Description1"),
|
||||
Error.Validation("Code1", "Description2"),
|
||||
Error.Validation("Code2", "Description3")
|
||||
];
|
||||
|
||||
// Act
|
||||
IResult result = _sut.TestValidationProblem(errors);
|
||||
|
||||
// Assert
|
||||
result.Should().BeOfType<ProblemHttpResult>();
|
||||
ProblemHttpResult problemDetails = (ProblemHttpResult)result;
|
||||
HttpValidationProblemDetails validationProblemDetails = (HttpValidationProblemDetails)problemDetails.ProblemDetails;
|
||||
validationProblemDetails.Errors.Should().ContainKeys("Code1", "Code2");
|
||||
validationProblemDetails.Errors["Code1"].Should().BeEquivalentTo(["Description1", "Description2"]);
|
||||
validationProblemDetails.Errors["Code2"].Should().BeEquivalentTo(["Description3"]);
|
||||
}
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Common;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Common.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="BaseEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class BaseEndpointFixture : BaseEndpoint<object, object>
|
||||
{
|
||||
/// <summary>
|
||||
/// Returns a standardized error response using the <see cref="ProblemDetails"/> format.
|
||||
/// </summary>
|
||||
/// <param name="errors">A list of errors to include in the response.</param>
|
||||
/// <returns>An <see cref="IResult"/> with the problem details containing the specified errors.</returns>
|
||||
public IResult TestProblem(List<Error> errors)
|
||||
{
|
||||
return Problem(errors);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns a standardized validation error response using the <see cref="ValidationProblemDetails"/> format.
|
||||
/// </summary>
|
||||
/// <param name="errors">A list of validation errors to include in the response.</param>
|
||||
/// <returns>An <see cref="IResult"/> with the validation problem details containing the specified errors.</returns>
|
||||
public IResult TestValidationProblem(List<Error> errors)
|
||||
{
|
||||
return ValidationProblem(errors);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures the API endpoint.
|
||||
/// </summary>
|
||||
public override void Configure()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the API request.
|
||||
/// </summary>
|
||||
/// <param name="request">The request containing the file system path for which to get the root.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public override Task<object> ExecuteAsync(object request, CancellationToken cancellationToken)
|
||||
{
|
||||
return Task.FromResult(new object());
|
||||
}
|
||||
}
|
||||
+167
@@ -0,0 +1,167 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using AutoFixture;
|
||||
using AutoFixture.AutoNSubstitute;
|
||||
using ErrorOr;
|
||||
using FastEndpoints;
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDirectories;
|
||||
using Lumina.Contracts.Requests.FileSystemManagement.Directories;
|
||||
using Lumina.Contracts.Responses.FileSystemManagement.Directories;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Directories.GetDirectories;
|
||||
using Mediator;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
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.Endpoints.FileSystemManagement.Directories;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetDirectoriesEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetDirectoriesEndpointTests
|
||||
{
|
||||
private readonly IFixture _fixture;
|
||||
private readonly ISender _mockSender;
|
||||
private readonly GetDirectoriesEndpoint _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetDirectoriesEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetDirectoriesEndpointTests()
|
||||
{
|
||||
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
|
||||
_mockSender = Substitute.For<ISender>();
|
||||
_sut = Factory.Create<GetDirectoriesEndpoint>(_mockSender);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldReturnOkResultWithDirectoryResponses()
|
||||
{
|
||||
// Arrange
|
||||
GetDirectoriesRequest request = _fixture.Create<GetDirectoriesRequest>();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
List<DirectoryResponse> expectedResponses = _fixture.CreateMany<DirectoryResponse>(3).ToList();
|
||||
_mockSender.Send(Arg.Any<GetDirectoriesQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From(expectedResponses.AsEnumerable()));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
IEnumerable<DirectoryResponse> actualResponses = result.Should().BeOfType<Ok<IEnumerable<DirectoryResponse>>>().Subject.Value!;
|
||||
actualResponses.Should().BeEquivalentTo(expectedResponses);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
GetDirectoriesRequest request = _fixture.Create<GetDirectoriesRequest>();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = Error.NotFound("Directory.NotFound", "The requested directory was not found.");
|
||||
_mockSender.Send(Arg.Any<GetDirectoriesQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
result.Should().BeOfType<ProblemHttpResult>();
|
||||
ProblemHttpResult problemDetails = (ProblemHttpResult)result;
|
||||
problemDetails.StatusCode.Should().Be(StatusCodes.Status404NotFound);
|
||||
problemDetails.ContentType.Should().Be("application/problem+json");
|
||||
problemDetails.ProblemDetails.Should().BeOfType<Microsoft.AspNetCore.Mvc.ProblemDetails>();
|
||||
|
||||
problemDetails.ProblemDetails.Title.Should().Be("Directory.NotFound");
|
||||
problemDetails.ProblemDetails.Detail.Should().Be("The requested directory was not found.");
|
||||
problemDetails.ProblemDetails.Status.Should().Be(StatusCodes.Status404NotFound);
|
||||
problemDetails.ProblemDetails.Type.Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
problemDetails.ProblemDetails.Extensions["traceId"].Should().NotBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenMediatorReturnsValidationError_ShouldReturnValidationProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
GetDirectoriesRequest request = _fixture.Create<GetDirectoriesRequest>();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = Error.Validation("Path.Invalid", "The provided path is invalid.");
|
||||
_mockSender.Send(Arg.Any<GetDirectoriesQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
result.Should().BeOfType<ProblemHttpResult>();
|
||||
ProblemHttpResult problemDetails = (ProblemHttpResult)result;
|
||||
problemDetails.StatusCode.Should().Be(StatusCodes.Status422UnprocessableEntity);
|
||||
problemDetails.ContentType.Should().Be("application/problem+json");
|
||||
problemDetails.ProblemDetails.Should().BeOfType<HttpValidationProblemDetails>();
|
||||
HttpValidationProblemDetails validationProblemDetails = (HttpValidationProblemDetails)problemDetails.ProblemDetails;
|
||||
validationProblemDetails.Status.Should().Be(StatusCodes.Status422UnprocessableEntity);
|
||||
validationProblemDetails.Title.Should().Be("Validation Error");
|
||||
validationProblemDetails.Detail.Should().Be("One or more validation errors occurred.");
|
||||
validationProblemDetails.Type.Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2");
|
||||
validationProblemDetails.Errors.Should().ContainSingle()
|
||||
.Which.Should().BeEquivalentTo(new
|
||||
{
|
||||
Key = "Path.Invalid",
|
||||
Value = new[] { "The provided path is invalid." }
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendGetDirectoriesQueryToMediator()
|
||||
{
|
||||
// Arrange
|
||||
GetDirectoriesRequest request = _fixture.Create<GetDirectoriesRequest>();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockSender.Send(Arg.Any<GetDirectoriesQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From(Enumerable.Empty<DirectoryResponse>()));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockSender.Received(1).Send(
|
||||
Arg.Is<GetDirectoriesQuery>(q => q.Path == request.Path && q.IncludeHiddenElements == request.IncludeHiddenElements),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
GetDirectoriesRequest request = _fixture.Create<GetDirectoriesRequest>();
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockSender.Send(Arg.Any<GetDirectoriesQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => new ValueTask<ErrorOr<IEnumerable<DirectoryResponse>>>(Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return ErrorOrFactory.From(_fixture.CreateMany<DirectoryResponse>(3).AsEnumerable());
|
||||
}, callInfo.Arg<CancellationToken>())));
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
}
|
||||
+170
@@ -0,0 +1,170 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using AutoFixture;
|
||||
using AutoFixture.AutoNSubstitute;
|
||||
using ErrorOr;
|
||||
using FastEndpoints;
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDirectoryTree;
|
||||
using Lumina.Contracts.Requests.FileSystemManagement.Directories;
|
||||
using Lumina.Contracts.Responses.FileSystemManagement.Common;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Directories.GetDirectoryTree;
|
||||
using Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures;
|
||||
using Mediator;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
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.Endpoints.FileSystemManagement.Directories;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetDirectoryTreeEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetDirectoryTreeEndpointTests
|
||||
{
|
||||
private readonly IFixture _fixture;
|
||||
private readonly ISender _mockSender;
|
||||
private readonly GetDirectoryTreeEndpoint _sut;
|
||||
private readonly FileSystemTreeNodeResponseFixture _fileSystemTreeNodeResponseFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetDirectoryTreeEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetDirectoryTreeEndpointTests()
|
||||
{
|
||||
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
|
||||
_mockSender = Substitute.For<ISender>();
|
||||
_sut = Factory.Create<GetDirectoryTreeEndpoint>(_mockSender);
|
||||
_fileSystemTreeNodeResponseFixture = new FileSystemTreeNodeResponseFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldReturnOkResultWithFileSystemTreeNodeResponses()
|
||||
{
|
||||
// Arrange
|
||||
GetDirectoryTreeRequest request = _fixture.Create<GetDirectoryTreeRequest>();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
List<FileSystemTreeNodeResponse> expectedResponses = _fileSystemTreeNodeResponseFixture.CreateMany(3, 3, 5);
|
||||
_mockSender.Send(Arg.Any<GetDirectoryTreeQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From(expectedResponses.AsEnumerable()));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
IEnumerable<FileSystemTreeNodeResponse> actualResponses = result.Should().BeOfType<Ok<IEnumerable<FileSystemTreeNodeResponse>>>().Subject.Value!;
|
||||
actualResponses.Should().BeEquivalentTo(expectedResponses);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
GetDirectoryTreeRequest request = _fixture.Create<GetDirectoryTreeRequest>();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = Error.NotFound("Directory.NotFound", "The requested directory was not found.");
|
||||
_mockSender.Send(Arg.Any<GetDirectoryTreeQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
result.Should().BeOfType<ProblemHttpResult>();
|
||||
ProblemHttpResult problemDetails = (ProblemHttpResult)result;
|
||||
problemDetails.StatusCode.Should().Be(StatusCodes.Status404NotFound);
|
||||
problemDetails.ContentType.Should().Be("application/problem+json");
|
||||
problemDetails.ProblemDetails.Should().BeOfType<Microsoft.AspNetCore.Mvc.ProblemDetails>();
|
||||
|
||||
problemDetails.ProblemDetails.Title.Should().Be("Directory.NotFound");
|
||||
problemDetails.ProblemDetails.Detail.Should().Be("The requested directory was not found.");
|
||||
problemDetails.ProblemDetails.Status.Should().Be(StatusCodes.Status404NotFound);
|
||||
problemDetails.ProblemDetails.Type.Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
problemDetails.ProblemDetails.Extensions["traceId"].Should().NotBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenMediatorReturnsValidationError_ShouldReturnValidationProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
GetDirectoryTreeRequest request = _fixture.Create<GetDirectoryTreeRequest>();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = Error.Validation("Path.Invalid", "The provided path is invalid.");
|
||||
_mockSender.Send(Arg.Any<GetDirectoryTreeQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
result.Should().BeOfType<ProblemHttpResult>();
|
||||
ProblemHttpResult problemDetails = (ProblemHttpResult)result;
|
||||
problemDetails.StatusCode.Should().Be(StatusCodes.Status422UnprocessableEntity);
|
||||
problemDetails.ContentType.Should().Be("application/problem+json");
|
||||
problemDetails.ProblemDetails.Should().BeOfType<HttpValidationProblemDetails>();
|
||||
HttpValidationProblemDetails validationProblemDetails = (HttpValidationProblemDetails)problemDetails.ProblemDetails;
|
||||
validationProblemDetails.Status.Should().Be(StatusCodes.Status422UnprocessableEntity);
|
||||
validationProblemDetails.Title.Should().Be("Validation Error");
|
||||
validationProblemDetails.Detail.Should().Be("One or more validation errors occurred.");
|
||||
validationProblemDetails.Type.Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2");
|
||||
validationProblemDetails.Errors.Should().ContainSingle()
|
||||
.Which.Should().BeEquivalentTo(new
|
||||
{
|
||||
Key = "Path.Invalid",
|
||||
Value = new[] { "The provided path is invalid." }
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendGetDirectoryTreeQueryToMediator()
|
||||
{
|
||||
// Arrange
|
||||
GetDirectoryTreeRequest request = _fixture.Create<GetDirectoryTreeRequest>();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockSender.Send(Arg.Any<GetDirectoryTreeQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From(Enumerable.Empty<FileSystemTreeNodeResponse>()));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockSender.Received(1).Send(
|
||||
Arg.Is<GetDirectoryTreeQuery>(q => q.Path == request.Path && q.IncludeFiles == request.IncludeFiles && q.IncludeHiddenElements == request.IncludeHiddenElements),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
GetDirectoryTreeRequest request = _fixture.Create<GetDirectoryTreeRequest>();
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockSender.Send(Arg.Any<GetDirectoryTreeQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => new ValueTask<ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>>(Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return ErrorOrFactory.From(_fileSystemTreeNodeResponseFixture.CreateMany(3, 3, 5).AsEnumerable());
|
||||
}, callInfo.Arg<CancellationToken>())));
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
}
|
||||
+170
@@ -0,0 +1,170 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using AutoFixture;
|
||||
using AutoFixture.AutoNSubstitute;
|
||||
using ErrorOr;
|
||||
using FastEndpoints;
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetTreeDirectories;
|
||||
using Lumina.Contracts.Requests.FileSystemManagement.Directories;
|
||||
using Lumina.Contracts.Responses.FileSystemManagement.Common;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Directories.GetTreeDirectories;
|
||||
using Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures;
|
||||
using Mediator;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
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.Endpoints.FileSystemManagement.Directories;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetTreeDirectoriesEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetTreeDirectoriesEndpointTests
|
||||
{
|
||||
private readonly IFixture _fixture;
|
||||
private readonly ISender _mockSender;
|
||||
private readonly GetTreeDirectoriesEndpoint _sut;
|
||||
private readonly FileSystemTreeNodeResponseFixture _fileSystemTreeNodeResponseFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetTreeDirectoriesEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetTreeDirectoriesEndpointTests()
|
||||
{
|
||||
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
|
||||
_mockSender = Substitute.For<ISender>();
|
||||
_sut = Factory.Create<GetTreeDirectoriesEndpoint>(_mockSender);
|
||||
_fileSystemTreeNodeResponseFixture = new FileSystemTreeNodeResponseFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldReturnOkResultWithFileSystemTreeNodeResponses()
|
||||
{
|
||||
// Arrange
|
||||
GetTreeDirectoriesRequest request = _fixture.Create<GetTreeDirectoriesRequest>();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
List<FileSystemTreeNodeResponse> expectedResponses = _fileSystemTreeNodeResponseFixture.CreateMany(3, 3, 5);
|
||||
_mockSender.Send(Arg.Any<GetTreeDirectoriesQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From(expectedResponses.AsEnumerable()));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
IEnumerable<FileSystemTreeNodeResponse> actualResponses = result.Should().BeOfType<Ok<IEnumerable<FileSystemTreeNodeResponse>>>().Subject.Value!;
|
||||
actualResponses.Should().BeEquivalentTo(expectedResponses);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
GetTreeDirectoriesRequest request = _fixture.Create<GetTreeDirectoriesRequest>();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = Error.NotFound("Directory.NotFound", "The requested directory was not found.");
|
||||
_mockSender.Send(Arg.Any<GetTreeDirectoriesQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
result.Should().BeOfType<ProblemHttpResult>();
|
||||
ProblemHttpResult problemDetails = (ProblemHttpResult)result;
|
||||
problemDetails.StatusCode.Should().Be(StatusCodes.Status404NotFound);
|
||||
problemDetails.ContentType.Should().Be("application/problem+json");
|
||||
problemDetails.ProblemDetails.Should().BeOfType<Microsoft.AspNetCore.Mvc.ProblemDetails>();
|
||||
|
||||
problemDetails.ProblemDetails.Title.Should().Be("Directory.NotFound");
|
||||
problemDetails.ProblemDetails.Detail.Should().Be("The requested directory was not found.");
|
||||
problemDetails.ProblemDetails.Status.Should().Be(StatusCodes.Status404NotFound);
|
||||
problemDetails.ProblemDetails.Type.Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
problemDetails.ProblemDetails.Extensions["traceId"].Should().NotBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenMediatorReturnsValidationError_ShouldReturnValidationProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
GetTreeDirectoriesRequest request = _fixture.Create<GetTreeDirectoriesRequest>();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = Error.Validation("Path.Invalid", "The provided path is invalid.");
|
||||
_mockSender.Send(Arg.Any<GetTreeDirectoriesQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
result.Should().BeOfType<ProblemHttpResult>();
|
||||
ProblemHttpResult problemDetails = (ProblemHttpResult)result;
|
||||
problemDetails.StatusCode.Should().Be(StatusCodes.Status422UnprocessableEntity);
|
||||
problemDetails.ContentType.Should().Be("application/problem+json");
|
||||
problemDetails.ProblemDetails.Should().BeOfType<HttpValidationProblemDetails>();
|
||||
HttpValidationProblemDetails validationProblemDetails = (HttpValidationProblemDetails)problemDetails.ProblemDetails;
|
||||
validationProblemDetails.Status.Should().Be(StatusCodes.Status422UnprocessableEntity);
|
||||
validationProblemDetails.Title.Should().Be("Validation Error");
|
||||
validationProblemDetails.Detail.Should().Be("One or more validation errors occurred.");
|
||||
validationProblemDetails.Type.Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2");
|
||||
validationProblemDetails.Errors.Should().ContainSingle()
|
||||
.Which.Should().BeEquivalentTo(new
|
||||
{
|
||||
Key = "Path.Invalid",
|
||||
Value = new[] { "The provided path is invalid." }
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendGetTreeDirectoriesQueryToMediator()
|
||||
{
|
||||
// Arrange
|
||||
GetTreeDirectoriesRequest request = _fixture.Create<GetTreeDirectoriesRequest>();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockSender.Send(Arg.Any<GetTreeDirectoriesQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From(Enumerable.Empty<FileSystemTreeNodeResponse>()));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockSender.Received(1).Send(
|
||||
Arg.Is<GetTreeDirectoriesQuery>(q => q.Path == request.Path && q.IncludeHiddenElements == request.IncludeHiddenElements),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
GetTreeDirectoriesRequest request = _fixture.Create<GetTreeDirectoriesRequest>();
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockSender.Send(Arg.Any<GetTreeDirectoriesQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => new ValueTask<ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>>(Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return ErrorOrFactory.From(_fileSystemTreeNodeResponseFixture.CreateMany(3, 3, 5).AsEnumerable());
|
||||
}, callInfo.Arg<CancellationToken>())));
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
}
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using FastEndpoints;
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Core.FileSystemManagement.Drives.Queries.GetDrives;
|
||||
using Lumina.Contracts.Responses.FileSystemManagement.Common;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Drives.GetDrives;
|
||||
using Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures;
|
||||
using Mediator;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
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.Endpoints.FileSystemManagement.Drives;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetDrivesEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetDrivesEndpointTests
|
||||
{
|
||||
private readonly ISender _mockSender;
|
||||
private readonly GetDrivesEndpoint _sut;
|
||||
private readonly FileSystemTreeNodeResponseFixture _fileSystemTreeNodeResponseFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DrivesControllerTests"/> class.
|
||||
/// </summary>
|
||||
public GetDrivesEndpointTests()
|
||||
{
|
||||
_mockSender = Substitute.For<ISender>();
|
||||
_fileSystemTreeNodeResponseFixture = new FileSystemTreeNodeResponseFixture();
|
||||
_sut = Factory.Create<GetDrivesEndpoint>(_mockSender);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldReturnOkResultWithFileSystemTreeNodeResponses()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
List<FileSystemTreeNodeResponse> expectedResponses = _fileSystemTreeNodeResponseFixture.CreateMany(3, 1, 1);
|
||||
_mockSender.Send(Arg.Any<GetDrivesQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From(expectedResponses.AsEnumerable()));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(new EmptyRequest(), cancellationToken);
|
||||
|
||||
// Assert
|
||||
IEnumerable<FileSystemTreeNodeResponse> actualResponses = result.Should().BeOfType<Ok<IEnumerable<FileSystemTreeNodeResponse>>>().Subject.Value!;
|
||||
actualResponses.Should().BeEquivalentTo(expectedResponses);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = Error.NotFound("Drive.NotFound", "The requested drive was not found.");
|
||||
_mockSender.Send(Arg.Any<GetDrivesQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(new EmptyRequest(), cancellationToken);
|
||||
|
||||
// Assert
|
||||
result.Should().BeOfType<ProblemHttpResult>();
|
||||
ProblemHttpResult problemDetails = (ProblemHttpResult)result;
|
||||
problemDetails.StatusCode.Should().Be(StatusCodes.Status404NotFound);
|
||||
problemDetails.ContentType.Should().Be("application/problem+json");
|
||||
problemDetails.ProblemDetails.Should().BeOfType<Microsoft.AspNetCore.Mvc.ProblemDetails>();
|
||||
|
||||
problemDetails.ProblemDetails.Title.Should().Be("Drive.NotFound");
|
||||
problemDetails.ProblemDetails.Detail.Should().Be("The requested drive was not found.");
|
||||
problemDetails.ProblemDetails.Status.Should().Be(StatusCodes.Status404NotFound);
|
||||
problemDetails.ProblemDetails.Type.Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
problemDetails.ProblemDetails.Extensions["traceId"].Should().NotBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendGetDrivesQueryToMediator()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockSender.Send(Arg.Any<GetDrivesQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From(Enumerable.Empty<FileSystemTreeNodeResponse>()));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(new EmptyRequest(), cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockSender.Received(1).Send(Arg.Any<GetDrivesQuery>(), Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockSender.Send(Arg.Any<GetDrivesQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => new ValueTask<ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>>(Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return ErrorOrFactory.From(_fileSystemTreeNodeResponseFixture.CreateMany(3, 1, 1).AsEnumerable());
|
||||
}, callInfo.Arg<CancellationToken>())));
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(new EmptyRequest(), cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
}
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Core.FileSystemManagement.FileSystem.Queries.GetFileSystem;
|
||||
using Lumina.Contracts.Enums.FileSystem;
|
||||
using Lumina.Contracts.Responses.FileSystemManagement.FileSystem;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.FileSystem.GetType;
|
||||
using Mediator;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.FileSystem;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetTypeEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetFileSystemTypeEndpointTests
|
||||
{
|
||||
private readonly ISender _mockSender;
|
||||
private readonly GetTypeEndpoint _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetFileSystemTypeEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetFileSystemTypeEndpointTests()
|
||||
{
|
||||
_mockSender = Substitute.For<ISender>();
|
||||
_sut = Factory.Create<GetTypeEndpoint>(_mockSender);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldReturnOkResultWithFileSystemTypeResponse()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
FileSystemTypeResponse expectedResponse = new(PlatformType.Windows);
|
||||
_mockSender.Send(Arg.Any<GetFileSystemQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedResponse);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(new EmptyRequest(), cancellationToken);
|
||||
|
||||
// Assert
|
||||
Ok<FileSystemTypeResponse> okResult = result.Should().BeOfType<Ok<FileSystemTypeResponse>>().Subject;
|
||||
okResult.Value.Should().BeEquivalentTo(expectedResponse);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(PlatformType.Windows)]
|
||||
[InlineData(PlatformType.Unix)]
|
||||
public async Task ExecuteAsync_WithDifferentPlatformTypes_ShouldReturnCorrectResponse(PlatformType platformType)
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
FileSystemTypeResponse expectedResponse = new(platformType);
|
||||
_mockSender.Send(Arg.Any<GetFileSystemQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedResponse);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(new EmptyRequest(), cancellationToken);
|
||||
|
||||
// Assert
|
||||
Ok<FileSystemTypeResponse> okResult = result.Should().BeOfType<Ok<FileSystemTypeResponse>>().Subject;
|
||||
okResult.Value!.PlatformType.Should().Be(platformType);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendGetFileSystemQueryToMediator()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockSender.Send(Arg.Any<GetFileSystemQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new FileSystemTypeResponse(PlatformType.Windows));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(new EmptyRequest(), cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockSender.Received(1).Send(Arg.Any<GetFileSystemQuery>(), Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockSender.Send(Arg.Any<GetFileSystemQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => new ValueTask<FileSystemTypeResponse>(Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return new FileSystemTypeResponse(PlatformType.Windows);
|
||||
}, callInfo.Arg<CancellationToken>())));
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(new EmptyRequest(), cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
}
|
||||
+170
@@ -0,0 +1,170 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using AutoFixture;
|
||||
using AutoFixture.AutoNSubstitute;
|
||||
using ErrorOr;
|
||||
using FastEndpoints;
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Core.FileSystemManagement.Files.Queries.GetFiles;
|
||||
using Lumina.Contracts.Requests.FileSystemManagement.Files;
|
||||
using Lumina.Contracts.Responses.FileSystemManagement.Files;
|
||||
using Lumina.Presentation.Api.Common.Http;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Files.GetFiles;
|
||||
using Mediator;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Files;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetFilesEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetFilesEndpointTests
|
||||
{
|
||||
private readonly IFixture _fixture;
|
||||
private readonly ISender _mockSender;
|
||||
private readonly GetFilesEndpoint _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetFilesEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetFilesEndpointTests()
|
||||
{
|
||||
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
|
||||
_mockSender = Substitute.For<ISender>();
|
||||
_sut = Factory.Create<GetFilesEndpoint>(_mockSender);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldReturnOkResultWithFileResponses()
|
||||
{
|
||||
// Arrange
|
||||
GetFilesRequest request = _fixture.Create<GetFilesRequest>();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
List<FileResponse> expectedResponses = _fixture.CreateMany<FileResponse>(3).ToList();
|
||||
_mockSender.Send(Arg.Any<GetFilesQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From(expectedResponses.AsEnumerable()));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
IEnumerable<FileResponse> actualResponses = result.Should().BeOfType<Ok<IEnumerable<FileResponse>>>().Subject.Value!;
|
||||
actualResponses.Should().BeEquivalentTo(expectedResponses);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
GetFilesRequest request = _fixture.Create<GetFilesRequest>();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = Error.NotFound("File.NotFound", "The requested file was not found.");
|
||||
_mockSender.Send(Arg.Any<GetFilesQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
result.Should().BeOfType<ProblemHttpResult>();
|
||||
ProblemHttpResult problemDetails = (ProblemHttpResult)result;
|
||||
problemDetails.StatusCode.Should().Be(StatusCodes.Status404NotFound);
|
||||
problemDetails.ContentType.Should().Be("application/problem+json");
|
||||
problemDetails.ProblemDetails.Should().BeOfType<Microsoft.AspNetCore.Mvc.ProblemDetails>();
|
||||
|
||||
problemDetails.ProblemDetails.Title.Should().Be("File.NotFound");
|
||||
problemDetails.ProblemDetails.Detail.Should().Be("The requested file was not found.");
|
||||
problemDetails.ProblemDetails.Status.Should().Be(StatusCodes.Status404NotFound);
|
||||
problemDetails.ProblemDetails.Type.Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
problemDetails.ProblemDetails.Extensions["traceId"].Should().NotBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenMediatorReturnsValidationError_ShouldReturnValidationProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
GetFilesRequest request = _fixture.Create<GetFilesRequest>();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = Error.Validation("Path.Invalid", "The provided path is invalid.");
|
||||
_mockSender.Send(Arg.Any<GetFilesQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
result.Should().BeOfType<ProblemHttpResult>();
|
||||
ProblemHttpResult problemDetails = (ProblemHttpResult)result;
|
||||
problemDetails.StatusCode.Should().Be(StatusCodes.Status422UnprocessableEntity);
|
||||
problemDetails.ContentType.Should().Be("application/problem+json");
|
||||
problemDetails.ProblemDetails.Should().BeOfType<HttpValidationProblemDetails>();
|
||||
HttpValidationProblemDetails validationProblemDetails = (HttpValidationProblemDetails)problemDetails.ProblemDetails;
|
||||
validationProblemDetails.Status.Should().Be(StatusCodes.Status422UnprocessableEntity);
|
||||
validationProblemDetails.Title.Should().Be("Validation Error");
|
||||
validationProblemDetails.Detail.Should().Be("One or more validation errors occurred.");
|
||||
validationProblemDetails.Type.Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2");
|
||||
validationProblemDetails.Errors.Should().ContainSingle()
|
||||
.Which.Should().BeEquivalentTo(new
|
||||
{
|
||||
Key = "Path.Invalid",
|
||||
Value = new[] { "The provided path is invalid." }
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendGetFilesQueryToSender()
|
||||
{
|
||||
// Arrange
|
||||
GetFilesRequest request = _fixture.Create<GetFilesRequest>();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockSender.Send(Arg.Any<GetFilesQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From(Enumerable.Empty<FileResponse>()));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockSender.Received(1).Send(Arg.Is<GetFilesQuery>(q =>
|
||||
q.Path == request.Path &&
|
||||
q.IncludeHiddenElements == request.IncludeHiddenElements),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
GetFilesRequest request = _fixture.Create<GetFilesRequest>();
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockSender.Send(Arg.Any<GetFilesQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => new ValueTask<ErrorOr<IEnumerable<FileResponse>>>(Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return ErrorOrFactory.From(_fixture.CreateMany<FileResponse>(3).AsEnumerable());
|
||||
}, callInfo.Arg<CancellationToken>())));
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
}
|
||||
+171
@@ -0,0 +1,171 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using AutoFixture;
|
||||
using AutoFixture.AutoNSubstitute;
|
||||
using ErrorOr;
|
||||
using FastEndpoints;
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Core.FileSystemManagement.Files.Queries.GetTreeFiles;
|
||||
using Lumina.Contracts.Requests.FileSystemManagement.Files;
|
||||
using Lumina.Contracts.Responses.FileSystemManagement.Common;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Files.GetTreeFiles;
|
||||
using Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures;
|
||||
using Mediator;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
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.Endpoints.FileSystemManagement.Files;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetTreeFilesEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetTreeFilesEndpointTests
|
||||
{
|
||||
private readonly IFixture _fixture;
|
||||
private readonly ISender _mockSender;
|
||||
private readonly GetTreeFilesEndpoint _sut;
|
||||
private readonly FileSystemTreeNodeResponseFixture _fileSystemTreeNodeResponseFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetTreeFilesEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetTreeFilesEndpointTests()
|
||||
{
|
||||
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
|
||||
_mockSender = Substitute.For<ISender>();
|
||||
_fileSystemTreeNodeResponseFixture = new FileSystemTreeNodeResponseFixture();
|
||||
_sut = Factory.Create<GetTreeFilesEndpoint>(_mockSender);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldReturnOkResultWithFileSystemTreeNodeResponses()
|
||||
{
|
||||
// Arrange
|
||||
GetTreeFilesRequest request = _fixture.Create<GetTreeFilesRequest>();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
List<FileSystemTreeNodeResponse> expectedResponses = _fileSystemTreeNodeResponseFixture.CreateMany(3, 3, 5);
|
||||
_mockSender.Send(Arg.Any<GetTreeFilesQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From(expectedResponses.AsEnumerable()));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
IEnumerable<FileSystemTreeNodeResponse> actualResponses = result.Should().BeOfType<Ok<IEnumerable<FileSystemTreeNodeResponse>>>().Subject.Value!;
|
||||
actualResponses.Should().BeEquivalentTo(expectedResponses);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
GetTreeFilesRequest request = _fixture.Create<GetTreeFilesRequest>();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = Error.NotFound("File.NotFound", "The requested file was not found.");
|
||||
_mockSender.Send(Arg.Any<GetTreeFilesQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
result.Should().BeOfType<ProblemHttpResult>();
|
||||
ProblemHttpResult problemDetails = (ProblemHttpResult)result;
|
||||
problemDetails.StatusCode.Should().Be(StatusCodes.Status404NotFound);
|
||||
problemDetails.ContentType.Should().Be("application/problem+json");
|
||||
problemDetails.ProblemDetails.Should().BeOfType<Microsoft.AspNetCore.Mvc.ProblemDetails>();
|
||||
|
||||
problemDetails.ProblemDetails.Title.Should().Be("File.NotFound");
|
||||
problemDetails.ProblemDetails.Detail.Should().Be("The requested file was not found.");
|
||||
problemDetails.ProblemDetails.Status.Should().Be(StatusCodes.Status404NotFound);
|
||||
problemDetails.ProblemDetails.Type.Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
problemDetails.ProblemDetails.Extensions["traceId"].Should().NotBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenMediatorReturnsValidationError_ShouldReturnValidationProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
GetTreeFilesRequest request = _fixture.Create<GetTreeFilesRequest>();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = Error.Validation("Path.Invalid", "The provided path is invalid.");
|
||||
_mockSender.Send(Arg.Any<GetTreeFilesQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
result.Should().BeOfType<ProblemHttpResult>();
|
||||
ProblemHttpResult problemDetails = (ProblemHttpResult)result;
|
||||
problemDetails.StatusCode.Should().Be(StatusCodes.Status422UnprocessableEntity);
|
||||
problemDetails.ContentType.Should().Be("application/problem+json");
|
||||
problemDetails.ProblemDetails.Should().BeOfType<HttpValidationProblemDetails>();
|
||||
HttpValidationProblemDetails validationProblemDetails = (HttpValidationProblemDetails)problemDetails.ProblemDetails;
|
||||
validationProblemDetails.Status.Should().Be(StatusCodes.Status422UnprocessableEntity);
|
||||
validationProblemDetails.Title.Should().Be("Validation Error");
|
||||
validationProblemDetails.Detail.Should().Be("One or more validation errors occurred.");
|
||||
validationProblemDetails.Type.Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2");
|
||||
validationProblemDetails.Errors.Should().ContainSingle()
|
||||
.Which.Should().BeEquivalentTo(new
|
||||
{
|
||||
Key = "Path.Invalid",
|
||||
Value = new[] { "The provided path is invalid." }
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendGetTreeFilesQueryToSender()
|
||||
{
|
||||
// Arrange
|
||||
GetTreeFilesRequest request = _fixture.Create<GetTreeFilesRequest>();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockSender.Send(Arg.Any<GetTreeFilesQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From(Enumerable.Empty<FileSystemTreeNodeResponse>()));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockSender.Received(1).Send(Arg.Is<GetTreeFilesQuery>(q =>
|
||||
q.Path == request.Path &&
|
||||
q.IncludeHiddenElements == request.IncludeHiddenElements),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
GetTreeFilesRequest request = _fixture.Create<GetTreeFilesRequest>();
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockSender.Send(Arg.Any<GetTreeFilesQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => new ValueTask<ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>>(Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return ErrorOrFactory.From(_fileSystemTreeNodeResponseFixture.CreateMany(3, 3, 5).AsEnumerable());
|
||||
}, callInfo.Arg<CancellationToken>())));
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.Requests.FileSystemManagement.Path;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="CheckPathExistsRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class CheckPathExistsRequestFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a <see cref="CheckPathExistsRequest"/> with default or random values.
|
||||
/// </summary>
|
||||
/// <param name="path">The path to check.</param>
|
||||
/// <param name="includeHiddenElements">Whether to include hidden elements.</param>
|
||||
/// <returns>The created <see cref="CheckPathExistsRequest"/>.</returns>
|
||||
public CheckPathExistsRequest Create(string? path = null, bool? includeHiddenElements = null)
|
||||
{
|
||||
return new CheckPathExistsRequest(
|
||||
Path: path ?? _faker.System.FilePath(),
|
||||
IncludeHiddenElements: includeHiddenElements ?? _faker.Random.Bool()
|
||||
);
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.Requests.FileSystemManagement.Path;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="CombinePathRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class CombinePathRequestFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a <see cref="CombinePathRequest"/> with default or random values.
|
||||
/// </summary>
|
||||
/// <param name="originalPath">The original path.</param>
|
||||
/// <param name="newPath">The new path to combine.</param>
|
||||
/// <returns>The created <see cref="CombinePathRequest"/>.</returns>
|
||||
public CombinePathRequest Create(string? originalPath = null, string? newPath = null)
|
||||
{
|
||||
return new CombinePathRequest(
|
||||
OriginalPath: originalPath ?? _faker.System.DirectoryPath(),
|
||||
NewPath: newPath ?? _faker.System.FileName()
|
||||
);
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -1,13 +1,13 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.Enums.FileSystem;
|
||||
using Lumina.Contracts.Responses.FileManagement;
|
||||
using Lumina.Contracts.Responses.FileSystemManagement.Common;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.UnitTests.Core.Controllers.FileManagement.Fixtures;
|
||||
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="FileSystemTreeNodeResponse"/> class.
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.Requests.FileSystemManagement.Path;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GetPathParentRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetPathParentRequestFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a <see cref="GetPathParentRequest"/> with a default or random value.
|
||||
/// </summary>
|
||||
/// <param name="path">The path to get the parent of.</param>
|
||||
/// <returns>The created <see cref="GetPathParentRequest"/>.</returns>
|
||||
public GetPathParentRequest Create(string? path = null)
|
||||
{
|
||||
return new GetPathParentRequest(
|
||||
Path: path ?? _faker.System.FilePath()
|
||||
);
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.Requests.FileSystemManagement.Path;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GetPathRootRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetPathRootRequestFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a <see cref="GetPathRootRequest"/> with a default or random value.
|
||||
/// </summary>
|
||||
/// <param name="path">The path to get the root of.</param>
|
||||
/// <returns>The created <see cref="GetPathRootRequest"/>.</returns>
|
||||
public GetPathRootRequest Create(string? path = null)
|
||||
{
|
||||
return new GetPathRootRequest(
|
||||
Path: path ?? _faker.System.FilePath()
|
||||
);
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.Requests.FileSystemManagement.Thumbnails;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GetThumbnailRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetThumbnailRequestFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a <see cref="GetThumbnailRequest"/> with default or random values.
|
||||
/// </summary>
|
||||
/// <param name="path">The path of the file to get the thumbnail for.</param>
|
||||
/// <param name="quality">The quality of the thumbnail.</param>
|
||||
/// <returns>The created <see cref="GetThumbnailRequest"/>.</returns>
|
||||
public GetThumbnailRequest Create(string? path = null, int? quality = null)
|
||||
{
|
||||
return new GetThumbnailRequest(
|
||||
Path: path ?? _faker.System.FilePath(),
|
||||
Quality: quality ?? _faker.Random.Int(1, 100)
|
||||
);
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -1,12 +1,12 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.Responses.FileManagement;
|
||||
using Lumina.Contracts.Responses.FileSystemManagement.Path;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.UnitTests.Core.Controllers.FileManagement.Fixtures;
|
||||
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="PathSegmentResponse"/> class.
|
||||
+2
-2
@@ -1,12 +1,12 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.Responses.FileManagement;
|
||||
using Lumina.Contracts.Responses.FileSystemManagement.Path;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.UnitTests.Core.Controllers.FileManagement.Fixtures;
|
||||
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="PathSeparatorResponse"/> class.
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.Requests.FileSystemManagement.Path;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="SplitPathRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SplitPathRequestFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a <see cref="SplitPathRequest"/> with a default or random value.
|
||||
/// </summary>
|
||||
/// <param name="path">The path to split.</param>
|
||||
/// <returns>The created <see cref="SplitPathRequest"/>.</returns>
|
||||
public SplitPathRequest Create(string? path = null)
|
||||
{
|
||||
return new SplitPathRequest(
|
||||
Path: path ?? _faker.System.FilePath()
|
||||
);
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -1,11 +1,11 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.Enums.PhotoLibrary;
|
||||
using Lumina.Contracts.Responses.FileManagement;
|
||||
using Lumina.Contracts.Responses.FileSystemManagement.Thumbnails;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.UnitTests.Core.Controllers.FileManagement.Fixtures;
|
||||
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="ThumbnailResponse"/> class.
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.Requests.FileSystemManagement.Path;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="ValidatePathRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ValidatePathRequestFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a <see cref="ValidatePathRequest"/> with a default or random value.
|
||||
/// </summary>
|
||||
/// <param name="path">The path to validate.</param>
|
||||
/// <returns>The created <see cref="ValidatePathRequest"/>.</returns>
|
||||
public ValidatePathRequest Create(string? path = null)
|
||||
{
|
||||
return new ValidatePathRequest(
|
||||
Path: path ?? _faker.System.FilePath()
|
||||
);
|
||||
}
|
||||
}
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Core.FileSystemManagement.Paths.Queries.CheckPathExists;
|
||||
using Lumina.Contracts.Requests.FileSystemManagement.Path;
|
||||
using Lumina.Contracts.Responses.FileSystemManagement.Path;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.CheckPathExists;
|
||||
using Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures;
|
||||
using Mediator;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Path;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="CheckPathExistsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class CheckPathExistsEndpointTests
|
||||
{
|
||||
private readonly ISender _mockSender;
|
||||
private readonly CheckPathExistsEndpoint _sut;
|
||||
private readonly CheckPathExistsRequestFixture _checkPathExistsRequestFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CheckPathExistsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public CheckPathExistsEndpointTests()
|
||||
{
|
||||
_mockSender = Substitute.For<ISender>();
|
||||
_sut = Factory.Create<CheckPathExistsEndpoint>(_mockSender);
|
||||
_checkPathExistsRequestFixture = new CheckPathExistsRequestFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldReturnOkResultWithPathExistsResponse()
|
||||
{
|
||||
// Arrange
|
||||
CheckPathExistsRequest request = _checkPathExistsRequestFixture.Create(path: @"C:\Users\TestUser\Documents", includeHiddenElements: true);
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
PathExistsResponse expectedResponse = new(true);
|
||||
_mockSender.Send(Arg.Any<CheckPathExistsQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedResponse);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
PathExistsResponse actualResponse = result.Should().BeOfType<Ok<PathExistsResponse>>().Subject.Value!;
|
||||
actualResponse.Should().BeEquivalentTo(expectedResponse);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendCheckPathExistsQueryToMediator()
|
||||
{
|
||||
// Arrange
|
||||
CheckPathExistsRequest request = _checkPathExistsRequestFixture.Create(path: @"C:\Users\TestUser\Documents", includeHiddenElements: true);
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockSender.Send(Arg.Any<CheckPathExistsQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new PathExistsResponse(true));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockSender.Received(1).Send(
|
||||
Arg.Is<CheckPathExistsQuery>(q => q.Path == request.Path && q.IncludeHiddenElements == request.IncludeHiddenElements),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
CheckPathExistsRequest request = _checkPathExistsRequestFixture.Create(path: @"C:\Users\TestUser\Documents", includeHiddenElements: true);
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockSender.Send(Arg.Any<CheckPathExistsQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => new ValueTask<PathExistsResponse>(Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return new PathExistsResponse(true);
|
||||
}, callInfo.Arg<CancellationToken>())));
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
}
|
||||
+166
@@ -0,0 +1,166 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using FastEndpoints;
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Core.FileSystemManagement.Paths.Commands.CombinePath;
|
||||
using Lumina.Contracts.Requests.FileSystemManagement.Path;
|
||||
using Lumina.Contracts.Responses.FileSystemManagement.Path;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.CombinePath;
|
||||
using Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures;
|
||||
using Mediator;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Path;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="CombinePathEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class CombinePathEndpointTests
|
||||
{
|
||||
private readonly ISender _mockSender;
|
||||
private readonly CombinePathEndpoint _sut;
|
||||
private readonly PathSegmentResponseFixture _pathSegmentResponseFixture;
|
||||
private readonly CombinePathRequestFixture _combinePathRequestFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CombinePathEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public CombinePathEndpointTests()
|
||||
{
|
||||
_mockSender = Substitute.For<ISender>();
|
||||
_sut = Factory.Create<CombinePathEndpoint>(_mockSender);
|
||||
_pathSegmentResponseFixture = new PathSegmentResponseFixture();
|
||||
_combinePathRequestFixture = new CombinePathRequestFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldReturnOkResultWithPathSegmentResponse()
|
||||
{
|
||||
// Arrange
|
||||
CombinePathRequest request = _combinePathRequestFixture.Create("C:\\Users", "TestUser");
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
PathSegmentResponse expectedResponse = _pathSegmentResponseFixture.Create();
|
||||
_mockSender.Send(Arg.Any<CombinePathCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From(expectedResponse));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
PathSegmentResponse actualResponse = result.Should().BeOfType<Ok<PathSegmentResponse>>().Subject.Value!;
|
||||
actualResponse.Should().BeEquivalentTo(expectedResponse);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
CombinePathRequest request = _combinePathRequestFixture.Create("InvalidPath", "TestUser");
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = Error.NotFound("Path.NotFound", "The requested path was not found.");
|
||||
_mockSender.Send(Arg.Any<CombinePathCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
result.Should().BeOfType<ProblemHttpResult>();
|
||||
ProblemHttpResult problemDetails = (ProblemHttpResult)result;
|
||||
problemDetails.StatusCode.Should().Be(StatusCodes.Status404NotFound);
|
||||
problemDetails.ContentType.Should().Be("application/problem+json");
|
||||
problemDetails.ProblemDetails.Should().BeOfType<Microsoft.AspNetCore.Mvc.ProblemDetails>();
|
||||
|
||||
problemDetails.ProblemDetails.Title.Should().Be("Path.NotFound");
|
||||
problemDetails.ProblemDetails.Detail.Should().Be("The requested path was not found.");
|
||||
problemDetails.ProblemDetails.Status.Should().Be(StatusCodes.Status404NotFound);
|
||||
problemDetails.ProblemDetails.Type.Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
problemDetails.ProblemDetails.Extensions["traceId"].Should().NotBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenMediatorReturnsValidationError_ShouldReturnValidationProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
CombinePathRequest request = _combinePathRequestFixture.Create("InvalidPath", "TestUser");
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = Error.Validation("Path.Invalid", "The provided path is invalid.");
|
||||
_mockSender.Send(Arg.Any<CombinePathCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
result.Should().BeOfType<ProblemHttpResult>();
|
||||
ProblemHttpResult problemDetails = (ProblemHttpResult)result;
|
||||
problemDetails.StatusCode.Should().Be(StatusCodes.Status422UnprocessableEntity);
|
||||
problemDetails.ContentType.Should().Be("application/problem+json");
|
||||
problemDetails.ProblemDetails.Should().BeOfType<HttpValidationProblemDetails>();
|
||||
HttpValidationProblemDetails validationProblemDetails = (HttpValidationProblemDetails)problemDetails.ProblemDetails;
|
||||
validationProblemDetails.Status.Should().Be(StatusCodes.Status422UnprocessableEntity);
|
||||
validationProblemDetails.Title.Should().Be("Validation Error");
|
||||
validationProblemDetails.Detail.Should().Be("One or more validation errors occurred.");
|
||||
validationProblemDetails.Type.Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2");
|
||||
validationProblemDetails.Errors.Should().ContainSingle()
|
||||
.Which.Should().BeEquivalentTo(new
|
||||
{
|
||||
Key = "Path.Invalid",
|
||||
Value = new[] { "The provided path is invalid." }
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendCombinePathCommandToMediator()
|
||||
{
|
||||
// Arrange
|
||||
CombinePathRequest request = _combinePathRequestFixture.Create("C:\\Users", "TestUser");
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockSender.Send(Arg.Any<CombinePathCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From(_pathSegmentResponseFixture.Create()));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockSender.Received(1).Send(
|
||||
Arg.Is<CombinePathCommand>(c => c.OriginalPath == request.OriginalPath && c.NewPath == request.NewPath),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
CombinePathRequest request = _combinePathRequestFixture.Create("C:\\Users", "TestUser");
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockSender.Send(Arg.Any<CombinePathCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => new ValueTask<ErrorOr<PathSegmentResponse>>(Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return ErrorOrFactory.From(_pathSegmentResponseFixture.Create());
|
||||
}, callInfo.Arg<CancellationToken>())));
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
}
|
||||
+166
@@ -0,0 +1,166 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using FastEndpoints;
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathParent;
|
||||
using Lumina.Contracts.Requests.FileSystemManagement.Path;
|
||||
using Lumina.Contracts.Responses.FileSystemManagement.Path;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.GetPathParent;
|
||||
using Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures;
|
||||
using Mediator;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
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.Endpoints.FileSystemManagement.Path;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetPathParentEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetPathParentEndpointTests
|
||||
{
|
||||
private readonly ISender _mockSender;
|
||||
private readonly GetPathParentEndpoint _sut;
|
||||
private readonly PathSegmentResponseFixture _pathSegmentResponseFixture;
|
||||
private readonly GetPathParentRequestFixture _getPathParentRequestFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPathParentEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetPathParentEndpointTests()
|
||||
{
|
||||
_mockSender = Substitute.For<ISender>();
|
||||
_sut = Factory.Create<GetPathParentEndpoint>(_mockSender);
|
||||
_pathSegmentResponseFixture = new PathSegmentResponseFixture();
|
||||
_getPathParentRequestFixture = new GetPathParentRequestFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldReturnOkResultWithPathSegmentResponse()
|
||||
{
|
||||
// Arrange
|
||||
GetPathParentRequest request = _getPathParentRequestFixture.Create(@"C:\Users\TestUser");
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
IEnumerable<PathSegmentResponse> expectedResponse = _pathSegmentResponseFixture.CreateMany();
|
||||
_mockSender.Send(Arg.Any<GetPathParentQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From(expectedResponse));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
IEnumerable<PathSegmentResponse> actualResponse = result.Should().BeOfType<Ok<IEnumerable<PathSegmentResponse>>>().Subject.Value!;
|
||||
actualResponse.Should().BeEquivalentTo(expectedResponse);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
GetPathParentRequest request = _getPathParentRequestFixture.Create(@"C:\Users\TestUser");
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = Error.NotFound("Path.NotFound", "The requested path was not found.");
|
||||
_mockSender.Send(Arg.Any<GetPathParentQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
result.Should().BeOfType<ProblemHttpResult>();
|
||||
ProblemHttpResult problemDetails = (ProblemHttpResult)result;
|
||||
problemDetails.StatusCode.Should().Be(StatusCodes.Status404NotFound);
|
||||
problemDetails.ContentType.Should().Be("application/problem+json");
|
||||
problemDetails.ProblemDetails.Should().BeOfType<Microsoft.AspNetCore.Mvc.ProblemDetails>();
|
||||
|
||||
problemDetails.ProblemDetails.Title.Should().Be("Path.NotFound");
|
||||
problemDetails.ProblemDetails.Detail.Should().Be("The requested path was not found.");
|
||||
problemDetails.ProblemDetails.Status.Should().Be(StatusCodes.Status404NotFound);
|
||||
problemDetails.ProblemDetails.Type.Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
problemDetails.ProblemDetails.Extensions["traceId"].Should().NotBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenMediatorReturnsValidationError_ShouldReturnValidationProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
GetPathParentRequest request = _getPathParentRequestFixture.Create(@"InvalidPath");
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = Error.Validation("Path.Invalid", "The provided path is invalid.");
|
||||
_mockSender.Send(Arg.Any<GetPathParentQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
result.Should().BeOfType<ProblemHttpResult>();
|
||||
ProblemHttpResult problemDetails = (ProblemHttpResult)result;
|
||||
problemDetails.StatusCode.Should().Be(StatusCodes.Status422UnprocessableEntity);
|
||||
problemDetails.ContentType.Should().Be("application/problem+json");
|
||||
problemDetails.ProblemDetails.Should().BeOfType<HttpValidationProblemDetails>();
|
||||
HttpValidationProblemDetails validationProblemDetails = (HttpValidationProblemDetails)problemDetails.ProblemDetails;
|
||||
validationProblemDetails.Status.Should().Be(StatusCodes.Status422UnprocessableEntity);
|
||||
validationProblemDetails.Title.Should().Be("Validation Error");
|
||||
validationProblemDetails.Detail.Should().Be("One or more validation errors occurred.");
|
||||
validationProblemDetails.Type.Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2");
|
||||
validationProblemDetails.Errors.Should().ContainSingle()
|
||||
.Which.Should().BeEquivalentTo(new
|
||||
{
|
||||
Key = "Path.Invalid",
|
||||
Value = new[] { "The provided path is invalid." }
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendGetPathParentQueryToMediator()
|
||||
{
|
||||
// Arrange
|
||||
GetPathParentRequest request = _getPathParentRequestFixture.Create(@"C:\Users\TestUser");
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockSender.Send(Arg.Any<GetPathParentQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From(_pathSegmentResponseFixture.CreateMany().AsEnumerable()));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockSender.Received(1).Send(Arg.Is<GetPathParentQuery>(q => q.Path == request.Path), Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
GetPathParentRequest request = _getPathParentRequestFixture.Create(@"C:\Users\TestUser");
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockSender.Send(Arg.Any<GetPathParentQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => new ValueTask<ErrorOr<IEnumerable<PathSegmentResponse>>>(Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return ErrorOrFactory.From(_pathSegmentResponseFixture.CreateMany().AsEnumerable());
|
||||
}, callInfo.Arg<CancellationToken>())));
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
}
|
||||
+164
@@ -0,0 +1,164 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using FastEndpoints;
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathRoot;
|
||||
using Lumina.Contracts.Requests.FileSystemManagement.Path;
|
||||
using Lumina.Contracts.Responses.FileSystemManagement.Path;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.GetPathRoot;
|
||||
using Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures;
|
||||
using Mediator;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Path;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetPathRootEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetPathRootEndpointTests
|
||||
{
|
||||
private readonly ISender _mockSender;
|
||||
private readonly GetPathRootEndpoint _sut;
|
||||
private readonly PathSegmentResponseFixture _pathSegmentResponseFixture;
|
||||
private readonly GetPathRootRequestFixture _getPathRootRequestFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPathRootEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetPathRootEndpointTests()
|
||||
{
|
||||
_mockSender = Substitute.For<ISender>();
|
||||
_sut = Factory.Create<GetPathRootEndpoint>(_mockSender);
|
||||
_pathSegmentResponseFixture = new PathSegmentResponseFixture();
|
||||
_getPathRootRequestFixture = new GetPathRootRequestFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldReturnOkResultWithPathSegmentResponse()
|
||||
{
|
||||
// Arrange
|
||||
GetPathRootRequest request = _getPathRootRequestFixture.Create(@"C:\Users\TestUser");
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
PathSegmentResponse expectedResponse = _pathSegmentResponseFixture.Create();
|
||||
_mockSender.Send(Arg.Any<GetPathRootQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From(expectedResponse));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
PathSegmentResponse actualResponse = result.Should().BeOfType<Ok<PathSegmentResponse>>().Subject.Value!;
|
||||
actualResponse.Should().BeEquivalentTo(expectedResponse);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
GetPathRootRequest request = _getPathRootRequestFixture.Create(@"C:\Users\TestUser");
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = Error.NotFound("Path.NotFound", "The requested path was not found.");
|
||||
_mockSender.Send(Arg.Any<GetPathRootQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
result.Should().BeOfType<ProblemHttpResult>();
|
||||
ProblemHttpResult problemDetails = (ProblemHttpResult)result;
|
||||
problemDetails.StatusCode.Should().Be(StatusCodes.Status404NotFound);
|
||||
problemDetails.ContentType.Should().Be("application/problem+json");
|
||||
problemDetails.ProblemDetails.Should().BeOfType<Microsoft.AspNetCore.Mvc.ProblemDetails>();
|
||||
|
||||
problemDetails.ProblemDetails.Title.Should().Be("Path.NotFound");
|
||||
problemDetails.ProblemDetails.Detail.Should().Be("The requested path was not found.");
|
||||
problemDetails.ProblemDetails.Status.Should().Be(StatusCodes.Status404NotFound);
|
||||
problemDetails.ProblemDetails.Type.Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
problemDetails.ProblemDetails.Extensions["traceId"].Should().NotBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenMediatorReturnsValidationError_ShouldReturnValidationProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
GetPathRootRequest request = _getPathRootRequestFixture.Create(@"InvalidPath");
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = Error.Validation("Path.Invalid", "The provided path is invalid.");
|
||||
_mockSender.Send(Arg.Any<GetPathRootQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
result.Should().BeOfType<ProblemHttpResult>();
|
||||
ProblemHttpResult problemDetails = (ProblemHttpResult)result;
|
||||
problemDetails.StatusCode.Should().Be(StatusCodes.Status422UnprocessableEntity);
|
||||
problemDetails.ContentType.Should().Be("application/problem+json");
|
||||
problemDetails.ProblemDetails.Should().BeOfType<HttpValidationProblemDetails>();
|
||||
HttpValidationProblemDetails validationProblemDetails = (HttpValidationProblemDetails)problemDetails.ProblemDetails;
|
||||
validationProblemDetails.Status.Should().Be(StatusCodes.Status422UnprocessableEntity);
|
||||
validationProblemDetails.Title.Should().Be("Validation Error");
|
||||
validationProblemDetails.Detail.Should().Be("One or more validation errors occurred.");
|
||||
validationProblemDetails.Type.Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2");
|
||||
validationProblemDetails.Errors.Should().ContainSingle()
|
||||
.Which.Should().BeEquivalentTo(new
|
||||
{
|
||||
Key = "Path.Invalid",
|
||||
Value = new[] { "The provided path is invalid." }
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendGetPathRootQueryToMediator()
|
||||
{
|
||||
// Arrange
|
||||
GetPathRootRequest request = _getPathRootRequestFixture.Create(@"C:\Users\TestUser");
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockSender.Send(Arg.Any<GetPathRootQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From(_pathSegmentResponseFixture.Create()));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockSender.Received(1).Send(Arg.Is<GetPathRootQuery>(q => q.Path == request.Path), Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
GetPathRootRequest request = _getPathRootRequestFixture.Create(@"C:\Users\TestUser");
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockSender.Send(Arg.Any<GetPathRootQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => new ValueTask<ErrorOr<PathSegmentResponse>>(Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return ErrorOrFactory.From(_pathSegmentResponseFixture.Create());
|
||||
}, callInfo.Arg<CancellationToken>())));
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
}
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathSeparator;
|
||||
using Lumina.Contracts.Responses.FileSystemManagement.Path;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.GetPathSeparator;
|
||||
using Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures;
|
||||
using Mediator;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Path;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetPathSeparatorEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetPathSeparatorEndpointTests
|
||||
{
|
||||
private readonly ISender _mockSender;
|
||||
private readonly GetPathSeparatorEndpoint _sut;
|
||||
private readonly PathSeparatorResponseFixture _pathSeparatorResponseFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPathSeparatorEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetPathSeparatorEndpointTests()
|
||||
{
|
||||
_mockSender = Substitute.For<ISender>();
|
||||
_sut = Factory.Create<GetPathSeparatorEndpoint>(_mockSender);
|
||||
_pathSeparatorResponseFixture = new PathSeparatorResponseFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldReturnOkResultWithPathSeparatorResponse()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
PathSeparatorResponse expectedResponse = _pathSeparatorResponseFixture.Create();
|
||||
_mockSender.Send(Arg.Any<GetPathSeparatorQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedResponse);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(cancellationToken);
|
||||
|
||||
// Assert
|
||||
PathSeparatorResponse actualResponse = result.Should().BeOfType<Ok<PathSeparatorResponse>>().Subject.Value!;
|
||||
actualResponse.Should().BeEquivalentTo(expectedResponse);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendGetPathSeparatorQueryToMediator()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockSender.Send(Arg.Any<GetPathSeparatorQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_pathSeparatorResponseFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockSender.Received(1).Send(Arg.Any<GetPathSeparatorQuery>(), Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockSender.Send(Arg.Any<GetPathSeparatorQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => new ValueTask<PathSeparatorResponse>(Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return _pathSeparatorResponseFixture.Create();
|
||||
}, callInfo.Arg<CancellationToken>())));
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
}
|
||||
+144
@@ -0,0 +1,144 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using FastEndpoints;
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Core.FileSystemManagement.Paths.Commands.SplitPath;
|
||||
using Lumina.Contracts.Requests.FileSystemManagement.Path;
|
||||
using Lumina.Contracts.Responses.FileSystemManagement.Path;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.SplitPath;
|
||||
using Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures;
|
||||
using Mediator;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
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.Endpoints.FileSystemManagement.Path;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="SplitPathEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SplitPathEndpointTests
|
||||
{
|
||||
private readonly ISender _mockSender;
|
||||
private readonly SplitPathEndpoint _sut;
|
||||
private readonly PathSegmentResponseFixture _pathSegmentResponseFixture;
|
||||
private readonly SplitPathRequestFixture _splitPathRequestFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SplitPathEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public SplitPathEndpointTests()
|
||||
{
|
||||
_mockSender = Substitute.For<ISender>();
|
||||
_sut = Factory.Create<SplitPathEndpoint>(_mockSender);
|
||||
_pathSegmentResponseFixture = new PathSegmentResponseFixture();
|
||||
_splitPathRequestFixture = new SplitPathRequestFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldReturnOkResultWithPathSegmentResponses()
|
||||
{
|
||||
// Arrange
|
||||
SplitPathRequest request = _splitPathRequestFixture.Create(@"C:\Users\TestUser\Documents");
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
IEnumerable<PathSegmentResponse> expectedResponse = _pathSegmentResponseFixture.CreateMany();
|
||||
_mockSender.Send(Arg.Any<SplitPathCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From(expectedResponse));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
IEnumerable<PathSegmentResponse> actualResponse = result.Should().BeOfType<Ok<IEnumerable<PathSegmentResponse>>>().Subject.Value!;
|
||||
actualResponse.Should().BeEquivalentTo(expectedResponse);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
SplitPathRequest request = _splitPathRequestFixture.Create(@"InvalidPath");
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = Error.Validation("Path.Invalid", "The provided path is invalid.");
|
||||
_mockSender.Send(Arg.Any<SplitPathCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
result.Should().BeOfType<ProblemHttpResult>();
|
||||
ProblemHttpResult problemDetails = (ProblemHttpResult)result;
|
||||
problemDetails.StatusCode.Should().Be(StatusCodes.Status422UnprocessableEntity);
|
||||
problemDetails.ContentType.Should().Be("application/problem+json");
|
||||
problemDetails.ProblemDetails.Should().BeOfType<HttpValidationProblemDetails>();
|
||||
HttpValidationProblemDetails validationProblemDetails = (HttpValidationProblemDetails)problemDetails.ProblemDetails;
|
||||
validationProblemDetails.Status.Should().Be(StatusCodes.Status422UnprocessableEntity);
|
||||
validationProblemDetails.Title.Should().Be("Validation Error");
|
||||
validationProblemDetails.Detail.Should().Be("One or more validation errors occurred.");
|
||||
validationProblemDetails.Type.Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2");
|
||||
validationProblemDetails.Errors.Should().ContainSingle()
|
||||
.Which.Should().BeEquivalentTo(new
|
||||
{
|
||||
Key = "Path.Invalid",
|
||||
Value = new[] { "The provided path is invalid." }
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendSplitPathCommandToMediator()
|
||||
{
|
||||
// Arrange
|
||||
SplitPathRequest request = _splitPathRequestFixture.Create(@"C:\Users\TestUser\Documents");
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockSender.Send(Arg.Any<SplitPathCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From(_pathSegmentResponseFixture.CreateMany().AsEnumerable()));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockSender.Received(1).Send(
|
||||
Arg.Is<SplitPathCommand>(c => c.Path == request.Path),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
SplitPathRequest request = _splitPathRequestFixture.Create(@"C:\Users\TestUser\Documents");
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockSender.Send(Arg.Any<SplitPathCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => new ValueTask<ErrorOr<IEnumerable<PathSegmentResponse>>>(Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return ErrorOrFactory.From(new List<PathSegmentResponse>
|
||||
{
|
||||
_pathSegmentResponseFixture.Create()
|
||||
}.AsEnumerable());
|
||||
}, callInfo.Arg<CancellationToken>())));
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
}
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Core.FileSystemManagement.Paths.Queries.ValidatePath;
|
||||
using Lumina.Contracts.Requests.FileSystemManagement.Path;
|
||||
using Lumina.Contracts.Responses.FileSystemManagement.Path;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.ValidatePath;
|
||||
using Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures;
|
||||
using Mediator;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Path;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ValidatePathEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ValidatePathEndpointTests
|
||||
{
|
||||
private readonly ISender _mockSender;
|
||||
private readonly ValidatePathEndpoint _sut;
|
||||
private readonly ValidatePathRequestFixture _validatePathRequestFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ValidatePathEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public ValidatePathEndpointTests()
|
||||
{
|
||||
_mockSender = Substitute.For<ISender>();
|
||||
_sut = Factory.Create<ValidatePathEndpoint>(_mockSender);
|
||||
_validatePathRequestFixture = new ValidatePathRequestFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldReturnOkResultWithPathValidResponse()
|
||||
{
|
||||
// Arrange
|
||||
ValidatePathRequest request = _validatePathRequestFixture.Create(@"C:\Users\TestUser\Documents");
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
PathValidResponse expectedResponse = new(true);
|
||||
_mockSender.Send(Arg.Any<ValidatePathQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedResponse);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
PathValidResponse actualResponse = result.Should().BeOfType<Ok<PathValidResponse>>().Subject.Value!;
|
||||
actualResponse.Should().BeEquivalentTo(expectedResponse);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendValidatePathQueryToMediator()
|
||||
{
|
||||
// Arrange
|
||||
ValidatePathRequest request = _validatePathRequestFixture.Create(@"C:\Users\TestUser\Documents");
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockSender.Send(Arg.Any<ValidatePathQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new PathValidResponse(true));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockSender.Received(1).Send(
|
||||
Arg.Is<ValidatePathQuery>(q => q.Path == request.Path),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
ValidatePathRequest request = _validatePathRequestFixture.Create(@"C:\Users\TestUser\Documents");
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockSender.Send(Arg.Any<ValidatePathQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => new ValueTask<PathValidResponse>(Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return new PathValidResponse(true);
|
||||
}, callInfo.Arg<CancellationToken>())));
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
}
|
||||
+164
@@ -0,0 +1,164 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using FastEndpoints;
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Core.FileSystemManagement.Thumbnails.Queries.GetThumbnail;
|
||||
using Lumina.Contracts.Requests.FileSystemManagement.Thumbnails;
|
||||
using Lumina.Contracts.Responses.FileSystemManagement.Thumbnails;
|
||||
using Lumina.Presentation.Api.Common.Utilities;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Thumbnails.GetThumbnail;
|
||||
using Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures;
|
||||
using Mediator;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Thumbnails;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetThumbnailEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetThumbnailEndpointTests
|
||||
{
|
||||
private readonly ISender _mockSender;
|
||||
private readonly GetThumbnailEndpoint _sut;
|
||||
private readonly GetThumbnailRequestFixture _getThumbnailRequestFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetThumbnailEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetThumbnailEndpointTests()
|
||||
{
|
||||
_mockSender = Substitute.For<ISender>();
|
||||
_sut = Factory.Create<GetThumbnailEndpoint>(_mockSender);
|
||||
_getThumbnailRequestFixture = new GetThumbnailRequestFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldReturnFileResultWithThumbnailResponse()
|
||||
{
|
||||
// Arrange
|
||||
GetThumbnailRequest request = _getThumbnailRequestFixture.Create("/path/to/file.jpg", 80);
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
ThumbnailResponse expectedResponse = ThumbnailResponseFixture.CreateThumbnailResponse();
|
||||
_mockSender.Send(Arg.Any<GetThumbnailQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From(expectedResponse));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
FileContentHttpResult fileResult = result.Should().BeOfType<FileContentHttpResult>().Subject;
|
||||
fileResult.FileContents.ToArray().Should().BeEquivalentTo(expectedResponse.Bytes);
|
||||
fileResult.ContentType.Should().Be(MimeTypes.GetMimeType(expectedResponse.Type));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
GetThumbnailRequest request = _getThumbnailRequestFixture.Create("/path/to/nonexistent/file.jpg", 80);
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = Error.NotFound("Thumbnail.NotFound", "The requested thumbnail was not found.");
|
||||
_mockSender.Send(Arg.Any<GetThumbnailQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
result.Should().BeOfType<ProblemHttpResult>();
|
||||
ProblemHttpResult problemDetails = (ProblemHttpResult)result;
|
||||
problemDetails.StatusCode.Should().Be(StatusCodes.Status404NotFound);
|
||||
problemDetails.ContentType.Should().Be("application/problem+json");
|
||||
problemDetails.ProblemDetails.Should().BeOfType<Microsoft.AspNetCore.Mvc.ProblemDetails>();
|
||||
|
||||
problemDetails.ProblemDetails.Title.Should().Be("Thumbnail.NotFound");
|
||||
problemDetails.ProblemDetails.Detail.Should().Be("The requested thumbnail was not found.");
|
||||
problemDetails.ProblemDetails.Status.Should().Be(StatusCodes.Status404NotFound);
|
||||
problemDetails.ProblemDetails.Type.Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
problemDetails.ProblemDetails.Extensions["traceId"].Should().NotBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenMediatorReturnsValidationError_ShouldReturnValidationProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
GetThumbnailRequest request = _getThumbnailRequestFixture.Create("/path/to/nonexistent/file.jpg", 80);
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = Error.Validation("Path.Invalid", "The provided path is invalid.");
|
||||
_mockSender.Send(Arg.Any<GetThumbnailQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
result.Should().BeOfType<ProblemHttpResult>();
|
||||
ProblemHttpResult problemDetails = (ProblemHttpResult)result;
|
||||
problemDetails.StatusCode.Should().Be(StatusCodes.Status422UnprocessableEntity);
|
||||
problemDetails.ContentType.Should().Be("application/problem+json");
|
||||
problemDetails.ProblemDetails.Should().BeOfType<HttpValidationProblemDetails>();
|
||||
HttpValidationProblemDetails validationProblemDetails = (HttpValidationProblemDetails)problemDetails.ProblemDetails;
|
||||
validationProblemDetails.Status.Should().Be(StatusCodes.Status422UnprocessableEntity);
|
||||
validationProblemDetails.Title.Should().Be("Validation Error");
|
||||
validationProblemDetails.Detail.Should().Be("One or more validation errors occurred.");
|
||||
validationProblemDetails.Type.Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2");
|
||||
validationProblemDetails.Errors.Should().ContainSingle()
|
||||
.Which.Should().BeEquivalentTo(new
|
||||
{
|
||||
Key = "Path.Invalid",
|
||||
Value = new[] { "The provided path is invalid." }
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendGetThumbnailQueryToSender()
|
||||
{
|
||||
// Arrange
|
||||
GetThumbnailRequest request = _getThumbnailRequestFixture.Create("/path/to/file.jpg", 80);
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockSender.Send(Arg.Any<GetThumbnailQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ErrorOrFactory.From(ThumbnailResponseFixture.CreateThumbnailResponse()));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockSender.Received(1).Send(Arg.Is<GetThumbnailQuery>(q => q.Path == request.Path && q.Quality == request.Quality), Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
GetThumbnailRequest request = _getThumbnailRequestFixture.Create("/path/to/file.jpg", 80);
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockSender.Send(Arg.Any<GetThumbnailQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => new ValueTask<ErrorOr<ThumbnailResponse>>(Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return ErrorOrFactory.From(ThumbnailResponseFixture.CreateThumbnailResponse());
|
||||
}, callInfo.Arg<CancellationToken>())));
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.WrittenContentLibrary.BookLibrary.Books;
|
||||
internal class AddBookEndpointTests
|
||||
{
|
||||
}
|
||||
-114
@@ -1,114 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentAssertions;
|
||||
using Lumina.Presentation.Api.Common.ModelBinders;
|
||||
using Microsoft.AspNetCore.Mvc.ModelBinding;
|
||||
using Microsoft.Extensions.Primitives;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.UnitTests.Core.ModelBinders;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="UrlStringBinder"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UrlStringBinderTests
|
||||
{
|
||||
private readonly UrlStringBinder _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UrlStringBinderTests"/> class.
|
||||
/// </summary>
|
||||
public UrlStringBinderTests()
|
||||
{
|
||||
_sut = new UrlStringBinder();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task BindModelAsync_WhenBindingContextIsNull_ShouldThrowArgumentNullException()
|
||||
{
|
||||
// Arrange
|
||||
ModelBindingContext? bindingContext = null;
|
||||
|
||||
// Act & Assert
|
||||
await Assert.ThrowsAsync<ArgumentNullException>(() => _sut.BindModelAsync(bindingContext!));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task BindModelAsync_WhenValueProviderResultIsNone_ShouldReturnCompletedTask()
|
||||
{
|
||||
// Arrange
|
||||
ModelBindingContext mockBindingContext = Substitute.For<ModelBindingContext>();
|
||||
mockBindingContext.ValueProvider.GetValue(Arg.Any<string>()).Returns(ValueProviderResult.None);
|
||||
|
||||
// Act
|
||||
await _sut.BindModelAsync(mockBindingContext);
|
||||
|
||||
// Assert
|
||||
mockBindingContext.Result.Should().Be(ModelBindingResult.Failed());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task BindModelAsync_WhenFirstValueIsNull_ShouldSetFailedResult()
|
||||
{
|
||||
// Arrange
|
||||
ModelBindingContext mockBindingContext = Substitute.For<ModelBindingContext>();
|
||||
ValueProviderResult valueProviderResult = new(new StringValues((string?)null));
|
||||
mockBindingContext.ValueProvider.GetValue(Arg.Any<string>()).Returns(valueProviderResult);
|
||||
|
||||
// Act
|
||||
await _sut.BindModelAsync(mockBindingContext);
|
||||
|
||||
// Assert
|
||||
mockBindingContext.Result.Should().Be(ModelBindingResult.Failed());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task BindModelAsync_WhenFirstValueIsNullButValueProviderResultIsNotNone_ShouldSetFailedResult()
|
||||
{
|
||||
// Arrange
|
||||
ModelBindingContext mockBindingContext = Substitute.For<ModelBindingContext>();
|
||||
ValueProviderResult valueProviderResult = new(new StringValues([null]));
|
||||
mockBindingContext.ValueProvider.GetValue(Arg.Any<string>()).Returns(valueProviderResult);
|
||||
|
||||
// Act
|
||||
await _sut.BindModelAsync(mockBindingContext);
|
||||
|
||||
// Assert
|
||||
mockBindingContext.Result.Should().Be(ModelBindingResult.Failed());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task BindModelAsync_WhenValueIsProvided_ShouldDecodeAndSetSuccessResult()
|
||||
{
|
||||
// Arrange
|
||||
const string ENCODED_VALUE = "Hello%20World%21";
|
||||
const string DECODED_VALUE = "Hello World!";
|
||||
ModelBindingContext mockBindingContext = Substitute.For<ModelBindingContext>();
|
||||
mockBindingContext.ValueProvider.GetValue(Arg.Any<string>()).Returns(new ValueProviderResult(ENCODED_VALUE));
|
||||
|
||||
// Act
|
||||
await _sut.BindModelAsync(mockBindingContext);
|
||||
|
||||
// Assert
|
||||
mockBindingContext.Result.Should().Be(ModelBindingResult.Success(DECODED_VALUE));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task BindModelAsync_ShouldUseProvidedModelName()
|
||||
{
|
||||
// Arrange
|
||||
const string MODEL_NAME = "testModel";
|
||||
ModelBindingContext mockBindingContext = Substitute.For<ModelBindingContext>();
|
||||
mockBindingContext.ModelName.Returns(MODEL_NAME);
|
||||
|
||||
// Act
|
||||
await _sut.BindModelAsync(mockBindingContext);
|
||||
|
||||
// Assert
|
||||
mockBindingContext.ValueProvider.Received(1).GetValue(MODEL_NAME);
|
||||
}
|
||||
}
|
||||
+12
-6
@@ -13,14 +13,20 @@
|
||||
<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="coverlet.collector" Version="6.0.2">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="FluentAssertions" Version="6.12.1" />
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.1" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.1" />
|
||||
<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" />
|
||||
<PackageReference Include="xunit" Version="2.9.2" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
Reference in new issue
Block a user