mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 03: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
+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()
|
||||
);
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.Enums.FileSystem;
|
||||
using Lumina.Contracts.Responses.FileSystemManagement.Common;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="FileSystemTreeNodeResponse"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class FileSystemTreeNodeResponseFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a single <see cref="FileSystemTreeNodeResponse"/> with a nested structure.
|
||||
/// </summary>
|
||||
/// <param name="currentDepth">The current depth in the tree structure. Default is 0 (root level).</param>
|
||||
/// <param name="maxDepth">The maximum depth of the tree structure. Default is 2.</param>
|
||||
/// <param name="maxChildren">The maximum number of children for each node. Default is 3.</param>
|
||||
/// <returns>A <see cref="FileSystemTreeNodeResponse"/> with a nested structure.</returns>
|
||||
public FileSystemTreeNodeResponse Create(int currentDepth = 0, int maxDepth = 2, int maxChildren = 3)
|
||||
{
|
||||
FileSystemTreeNodeResponse response = new()
|
||||
{
|
||||
Path = _faker.System.FilePath(),
|
||||
Name = _faker.System.FileName(),
|
||||
ItemType = FileSystemItemType.Directory,
|
||||
IsExpanded = _faker.Random.Bool(),
|
||||
ChildrenLoaded = true,
|
||||
Children = []
|
||||
};
|
||||
if (currentDepth < maxDepth)
|
||||
{
|
||||
int childCount = _faker.Random.Int(1, maxChildren);
|
||||
for (int i = 0; i < childCount; i++)
|
||||
response.Children.Add(Create(currentDepth + 1, maxDepth, maxChildren));
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="FileSystemTreeNodeResponse"/> objects, each with a nested structure.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of root-level nodes to create. Default is 2.</param>
|
||||
/// <param name="maxDepth">The maximum depth of the tree structure for each root node. Default is 2.</param>
|
||||
/// <param name="maxChildren">The maximum number of children for each node. Default is 3.</param>
|
||||
/// <returns>A list of <see cref="FileSystemTreeNodeResponse"/> objects with nested structures.</returns>
|
||||
public List<FileSystemTreeNodeResponse> CreateMany(int count = 2, int maxDepth = 2, int maxChildren = 3)
|
||||
{
|
||||
return Enumerable.Range(0, count).Select(_ => Create(0, maxDepth, maxChildren)).ToList();
|
||||
}
|
||||
}
|
||||
+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)
|
||||
);
|
||||
}
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.Responses.FileSystemManagement.Path;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="PathSegmentResponse"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PathSegmentResponseFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="PathSegmentResponse"/>.
|
||||
/// </summary>
|
||||
/// <returns>The created <see cref="PathSegmentResponse"/>.</returns>
|
||||
public PathSegmentResponse Create()
|
||||
{
|
||||
return new PathSegmentResponse(_faker.System.DirectoryPath());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="PathSegmentResponse"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<PathSegmentResponse> CreateMany(int count = 3)
|
||||
{
|
||||
return Enumerable.Range(0, count).Select(_ => Create()).ToList();
|
||||
}
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.Responses.FileSystemManagement.Path;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="PathSeparatorResponse"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PathSeparatorResponseFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="PathSeparatorResponse"/>.
|
||||
/// </summary>
|
||||
/// <returns>The created <see cref="PathSeparatorResponse"/>.</returns>
|
||||
public PathSeparatorResponse Create()
|
||||
{
|
||||
return new PathSeparatorResponse(_faker.System.DirectoryPath());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="PathSeparatorResponse"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<PathSeparatorResponse> CreateMany(int count = 3)
|
||||
{
|
||||
return Enumerable.Range(0, count).Select(_ => Create()).ToList();
|
||||
}
|
||||
}
|
||||
+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()
|
||||
);
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.Enums.PhotoLibrary;
|
||||
using Lumina.Contracts.Responses.FileSystemManagement.Thumbnails;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.FileSystemManagement.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="ThumbnailResponse"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ThumbnailResponseFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid query to get a thumbnail.
|
||||
/// </summary>
|
||||
/// <returns>The created query.</returns>
|
||||
public static ThumbnailResponse CreateThumbnailResponse()
|
||||
{
|
||||
return new Faker<ThumbnailResponse>()
|
||||
.CustomInstantiator(f => new ThumbnailResponse(
|
||||
default,
|
||||
default!
|
||||
))
|
||||
.RuleFor(x => x.Type, f => f.PickRandom<ImageType>())
|
||||
.RuleFor(x => x.Bytes, f => f.Random.Bytes(20));
|
||||
}
|
||||
}
|
||||
+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
|
||||
{
|
||||
}
|
||||
Reference in new issue
Block a user