mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-02 21:11:10 +00:00
Adds plugin upload from the web client
This commit is contained in:
1 parent
d84823f6d2
commit
b3ffb5dfab
57 files changed
+2774
-16
No files matched your search
+129
@@ -0,0 +1,129 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Infrastructure.Plugins;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Core.Plugins.Commands.InstallPlugin;
|
||||
using Lumina.Application.Fixtures.Core.Plugins.Commands.InstallPlugin;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.Plugins.Commands.InstallPlugin;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="InstallPluginCommandHandler"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class InstallPluginCommandHandlerTests
|
||||
{
|
||||
private readonly IPluginInstaller _mockPluginInstaller;
|
||||
private readonly ICurrentUserService _mockCurrentUserService;
|
||||
private readonly IAuthorizationService _mockAuthorizationService;
|
||||
private readonly IValidator<InstallPluginCommand> _mockValidator;
|
||||
private readonly InstallPluginCommandHandler _sut;
|
||||
private readonly InstallPluginCommandFixture _installPluginCommandFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="InstallPluginCommandHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public InstallPluginCommandHandlerTests()
|
||||
{
|
||||
_mockPluginInstaller = Substitute.For<IPluginInstaller>();
|
||||
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
|
||||
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
|
||||
_mockValidator = Substitute.For<IValidator<InstallPluginCommand>>();
|
||||
_mockValidator.Validate(Arg.Any<InstallPluginCommand>()).Returns([]);
|
||||
_mockCurrentUserService.UserId.Returns(Guid.NewGuid());
|
||||
_mockAuthorizationService.IsInRoleAsync(Arg.Any<Guid>(), "Admin", Arg.Any<CancellationToken>()).Returns(true);
|
||||
_sut = new InstallPluginCommandHandler(_mockPluginInstaller, _mockCurrentUserService, _mockAuthorizationService, _mockValidator);
|
||||
_installPluginCommandFixture = new InstallPluginCommandFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenCalled_ShouldInstallThePlugin()
|
||||
{
|
||||
// Arrange
|
||||
InstallPluginCommand command = _installPluginCommandFixture.Create();
|
||||
_mockPluginInstaller.InstallAsync(Arg.Any<System.IO.Stream>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Success);
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
await _mockPluginInstaller.Received(1).InstallAsync(command.Archive!, command.FileName!, Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutInstalling()
|
||||
{
|
||||
// Arrange
|
||||
InstallPluginCommand command = _installPluginCommandFixture.Create();
|
||||
_mockValidator.Validate(Arg.Any<InstallPluginCommand>()).Returns([Errors.Plugins.PluginArchiveCannotBeNull]);
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Plugins.PluginArchiveCannotBeNull, result.FirstError);
|
||||
await _mockPluginInstaller.DidNotReceiveWithAnyArgs().InstallAsync(default!, default!, default);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenCurrentUserIsMissing_ShouldReturnNotAuthorizedWithoutInstalling()
|
||||
{
|
||||
// Arrange
|
||||
InstallPluginCommand command = _installPluginCommandFixture.Create();
|
||||
_mockCurrentUserService.UserId.Returns((Guid?)null);
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
|
||||
await _mockPluginInstaller.DidNotReceiveWithAnyArgs().InstallAsync(default!, default!, default);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenUserIsNotAdmin_ShouldReturnNotAuthorizedWithoutInstalling()
|
||||
{
|
||||
// Arrange
|
||||
InstallPluginCommand command = _installPluginCommandFixture.Create();
|
||||
_mockAuthorizationService.IsInRoleAsync(Arg.Any<Guid>(), "Admin", Arg.Any<CancellationToken>()).Returns(false);
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
|
||||
await _mockPluginInstaller.DidNotReceiveWithAnyArgs().InstallAsync(default!, default!, default);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenInstallationFails_ShouldReturnTheInstallationError()
|
||||
{
|
||||
// Arrange
|
||||
InstallPluginCommand command = _installPluginCommandFixture.Create();
|
||||
_mockPluginInstaller.InstallAsync(Arg.Any<System.IO.Stream>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Errors.Plugins.PluginArchiveNotReadable);
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Plugins.PluginArchiveNotReadable, result.FirstError);
|
||||
}
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.Plugins.Commands.InstallPlugin;
|
||||
using Lumina.Application.Fixtures.Core.Plugins.Commands.InstallPlugin;
|
||||
using Lumina.Application.UnitTests.Common.Setup;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.Plugins.Commands.InstallPlugin;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="InstallPluginCommandValidator"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class InstallPluginCommandValidatorTests
|
||||
{
|
||||
private readonly InstallPluginCommandValidator _validator = new();
|
||||
private readonly InstallPluginCommandFixture _installPluginCommandFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenArchiveIsNull_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
InstallPluginCommand command = _installPluginCommandFixture.Create() with { Archive = null };
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Plugins.PluginArchiveCannotBeNull);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenFileNameIsEmpty_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
InstallPluginCommand command = _installPluginCommandFixture.Create() with { FileName = string.Empty };
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Plugins.PluginFileNameCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
InstallPluginCommand command = _installPluginCommandFixture.Create();
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveAnyValidationErrors();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration;
|
||||
using Lumina.Application.Common.Infrastructure.Plugins;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Infrastructure.Core.Plugins;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.Plugins;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="PluginInstaller"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PluginInstallerTests : IDisposable
|
||||
{
|
||||
private readonly string _pluginsDirectory;
|
||||
private readonly PluginInstaller _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="PluginInstallerTests"/> class.
|
||||
/// </summary>
|
||||
public PluginInstallerTests()
|
||||
{
|
||||
_pluginsDirectory = Path.Combine(AppContext.BaseDirectory, $".test-plugins-{Guid.NewGuid():N}");
|
||||
ILogger<PluginInstaller> mockLogger = Substitute.For<ILogger<PluginInstaller>>();
|
||||
IOptions<PluginsSettingsDto> mockOptions = Substitute.For<IOptions<PluginsSettingsDto>>();
|
||||
mockOptions.Value.Returns(new PluginsSettingsDto { Directory = Path.GetFileName(_pluginsDirectory) });
|
||||
_sut = new PluginInstaller(mockOptions, mockLogger);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InstallAsync_WhenUploadingSingleAssembly_ShouldCopyAssemblyToPluginsDirectory()
|
||||
{
|
||||
// Arrange
|
||||
string assemblyName = "Lumina.TestPlugin.dll";
|
||||
await using FileStream stream = File.OpenRead(Path.Combine(AppContext.BaseDirectory, assemblyName));
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.InstallAsync(stream, assemblyName, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.True(File.Exists(Path.Combine(_pluginsDirectory, assemblyName)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InstallAsync_WhenUploadingZipWithAssemblies_ShouldExtractAssembliesFlattenedToPluginsDirectory()
|
||||
{
|
||||
// Arrange
|
||||
await using MemoryStream zipStream = new();
|
||||
CreateZipArchive(zipStream, [("nested/plugin/Lumina.TestPlugin.dll", ReadTestAssembly()), ("readme.txt", Encoding.UTF8.GetBytes("not an assembly"))]);
|
||||
zipStream.Position = 0;
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.InstallAsync(zipStream, "plugin.zip", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.True(File.Exists(Path.Combine(_pluginsDirectory, "Lumina.TestPlugin.dll")));
|
||||
Assert.False(File.Exists(Path.Combine(_pluginsDirectory, "readme.txt")));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InstallAsync_WhenUploadingUnsupportedFileType_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
await using MemoryStream stream = new([.. new byte[] { 1, 2, 3, 4 }]);
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.InstallAsync(stream, "plugin.txt", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Plugins.UnsupportedPluginFileType, result.FirstError);
|
||||
Assert.False(Directory.Exists(_pluginsDirectory));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InstallAsync_WhenUploadingZipWithoutAssemblies_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
await using MemoryStream zipStream = new();
|
||||
CreateZipArchive(zipStream, [("readme.txt", Encoding.UTF8.GetBytes("not an assembly"))]);
|
||||
zipStream.Position = 0;
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.InstallAsync(zipStream, "plugin.zip", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Plugins.PluginArchiveContainsNoAssemblies, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InstallAsync_WhenUploadingCorruptZip_ShouldReturnNotReadableError()
|
||||
{
|
||||
// Arrange
|
||||
await using MemoryStream stream = new([.. new byte[] { 1, 2, 3, 4 }]);
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.InstallAsync(stream, "plugin.zip", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Plugins.PluginArchiveNotReadable, result.FirstError);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes the temporary plugins directory created by the tests.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
if (Directory.Exists(_pluginsDirectory))
|
||||
Directory.Delete(_pluginsDirectory, recursive: true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an in-memory ZIP archive containing the provided entries.
|
||||
/// </summary>
|
||||
/// <param name="zipStream">The stream to write the archive into.</param>
|
||||
/// <param name="entries">The entries to add, as pairs of entry name and content.</param>
|
||||
private static void CreateZipArchive(MemoryStream zipStream, IEnumerable<(string Name, byte[] Content)> entries)
|
||||
{
|
||||
using ZipArchive zipArchive = new(zipStream, ZipArchiveMode.Create, leaveOpen: true);
|
||||
foreach ((string name, byte[] content) in entries)
|
||||
{
|
||||
ZipArchiveEntry entry = zipArchive.CreateEntry(name);
|
||||
using Stream entryStream = entry.Open();
|
||||
entryStream.Write(content);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the bytes of the <c>Lumina.TestPlugin.dll</c> assembly from the test output directory.
|
||||
/// </summary>
|
||||
/// <returns>The assembly bytes.</returns>
|
||||
private static byte[] ReadTestAssembly()
|
||||
{
|
||||
return File.ReadAllBytes(Path.Combine(AppContext.BaseDirectory, "Lumina.TestPlugin.dll"));
|
||||
}
|
||||
}
|
||||
+169
@@ -0,0 +1,169 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Application.Core.Plugins.Commands.InstallPlugin;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Plugins.InstallPlugin;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.Features;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Plugins.InstallPlugin;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="InstallPluginEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class InstallPluginEndpointTests
|
||||
{
|
||||
private readonly Application.Common.CQRS.ICommandHandler<InstallPluginCommand, Result<Success>> _mockHandler;
|
||||
private readonly InstallPluginEndpoint _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="InstallPluginEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public InstallPluginEndpointTests()
|
||||
{
|
||||
_mockHandler = Substitute.For<Application.Common.CQRS.ICommandHandler<InstallPluginCommand, Result<Success>>>();
|
||||
_sut = Factory.Create<InstallPluginEndpoint>(_mockHandler);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenArchiveUploaded_ShouldReturnOkResult()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<InstallPluginCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Success));
|
||||
ConfigureFormWithArchive([1, 2, 3, 4], "plugin.zip");
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
Assert.IsType<Ok>(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenArchiveUploaded_ShouldSendInstallPluginCommandWithUploadedStreamAndFileName()
|
||||
{
|
||||
// Arrange
|
||||
byte[] content = [1, 2, 3, 4];
|
||||
string fileName = "plugin.zip";
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<InstallPluginCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Success));
|
||||
ConfigureFormWithArchive(content, fileName);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<InstallPluginCommand>(command =>
|
||||
command.FileName == fileName &&
|
||||
command.Archive != null),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenNoArchiveUploaded_ShouldSendInstallPluginCommandWithNullArchiveAndFileName()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<InstallPluginCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Success));
|
||||
ConfigureFormWithoutFiles();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
Assert.IsType<Ok>(result);
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<InstallPluginCommand>(command =>
|
||||
command.Archive == null &&
|
||||
command.FileName == null),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = ApplicationErrors.Authorization.NotAuthorized;
|
||||
_mockHandler.HandleAsync(Arg.Any<InstallPluginCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
ConfigureFormWithArchive([1, 2, 3, 4], "plugin.zip");
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemDetails.ContentType);
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemDetails.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status);
|
||||
Assert.Equal("General.Unauthorized", problemDetailsBody.Title);
|
||||
Assert.Equal("NotAuthorized", problemDetailsBody.Detail);
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type);
|
||||
Assert.NotNull(problemDetailsBody.Extensions["traceId"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockHandler.HandleAsync(Arg.Any<InstallPluginCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return Result.From(Result.Success);
|
||||
}, callInfo.Arg<CancellationToken>()));
|
||||
ConfigureFormWithArchive([1, 2, 3, 4], "plugin.zip");
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(EmptyRequest.Instance, cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
|
||||
private void ConfigureFormWithArchive(byte[] content, string fileName)
|
||||
{
|
||||
// the stream stays open for the duration of the test, since the endpoint reads it through the form file during execution
|
||||
MemoryStream archiveStream = new(content);
|
||||
IFormFile formFile = new FormFile(archiveStream, 0, content.Length, "archive", fileName);
|
||||
FormFileCollection files = [formFile];
|
||||
IFormCollection form = new FormCollection([], files);
|
||||
_sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test";
|
||||
// a real FormFeature is used instead of a substitute, because the endpoint execution reads the form through the
|
||||
// request machinery, which would bypass a mocked feature and parse the (empty) request body
|
||||
_sut.HttpContext.Features.Set<IFormFeature>(new FormFeature(form));
|
||||
}
|
||||
|
||||
private void ConfigureFormWithoutFiles()
|
||||
{
|
||||
IFormCollection form = new FormCollection([]);
|
||||
_sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test";
|
||||
_sut.HttpContext.Features.Set<IFormFeature>(new FormFeature(form));
|
||||
}
|
||||
}
|
||||
+4
-3
@@ -4,10 +4,10 @@ using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.Plugins;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Plugins.GetPlugins;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
@@ -25,6 +25,7 @@ public class GetPluginsEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly GetPluginsEndpoint _sut;
|
||||
private readonly PluginDtoFixture _pluginDtoFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };
|
||||
|
||||
/// <summary>
|
||||
@@ -40,7 +41,7 @@ public class GetPluginsEndpointTests
|
||||
public async Task ExecuteAsync_WhenApiReturnsPlugins_ShouldReturnSuccessJsonWithPlugins()
|
||||
{
|
||||
// Arrange
|
||||
PluginDto[] expectedPlugins = [new PluginDto { Id = Guid.NewGuid(), Name = "OpenLibrary", Author = "Test Author", Version = "1.0.0" }];
|
||||
PluginDto[] expectedPlugins = [_pluginDtoFixture.Create(name: "OpenLibrary")];
|
||||
_mockApiHttpClient.GetAsync<PluginDto[]>(ApiRoutes.Plugins.GET_PLUGINS, Arg.Any<CancellationToken>())
|
||||
.Returns(expectedPlugins);
|
||||
|
||||
@@ -60,7 +61,7 @@ public class GetPluginsEndpointTests
|
||||
{
|
||||
// Arrange
|
||||
_mockApiHttpClient.GetAsync<PluginDto[]>(ApiRoutes.Plugins.GET_PLUGINS, Arg.Any<CancellationToken>())
|
||||
.Returns([new PluginDto { Id = Guid.NewGuid(), Name = "OpenLibrary" }]);
|
||||
.Returns([_pluginDtoFixture.Create(name: "OpenLibrary")]);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.Plugins;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Plugins.InstallPlugin;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.Features;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Plugins.InstallPlugin;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="InstallPluginEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class InstallPluginEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly InstallPluginEndpoint _sut;
|
||||
private readonly PluginDtoFixture _pluginDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="InstallPluginEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public InstallPluginEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<InstallPluginEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenArchiveUploaded_ShouldInstallPluginViaApiAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
byte[] content = [1, 2, 3, 4];
|
||||
string fileName = "plugin.zip";
|
||||
_mockApiHttpClient.PostMultipartAsync<PluginDto>(Arg.Any<string>(), Arg.Any<Stream>(), fileName, "archive", Arg.Any<CancellationToken>())
|
||||
.Returns(_pluginDtoFixture.Create());
|
||||
ConfigureFormWithArchive(content, fileName);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostMultipartAsync<PluginDto>(
|
||||
ApiRoutes.Plugins.INSTALL_PLUGIN,
|
||||
Arg.Any<Stream>(),
|
||||
fileName,
|
||||
"archive",
|
||||
Arg.Any<CancellationToken>());
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
}
|
||||
|
||||
private void ConfigureFormWithArchive(byte[] content, string fileName)
|
||||
{
|
||||
// the stream stays open for the duration of the test, since the endpoint reads it through the form file during execution
|
||||
MemoryStream archiveStream = new(content);
|
||||
IFormFile formFile = new FormFile(archiveStream, 0, content.Length, "archive", fileName);
|
||||
FormFileCollection files = [formFile];
|
||||
IFormCollection form = new FormCollection([], files);
|
||||
_sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test";
|
||||
_sut.HttpContext.Features.Set<IFormFeature>(new FormFeature(form));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user