Adds a restore action for soft deleted bundled themes

This commit is contained in:
BinaryAlley committed 2026-08-21 11:47:51 -07:00
1 parent 15945c2e56
commit 7e54c990ad
49 files changed
+1666 -26

No files matched your search

@@ -0,0 +1,32 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.Themes;
using Lumina.Application.Core.Themes.Management.Commands.RestoreTheme;
using Lumina.Contracts.Fixtures.Core.Requests.Themes;
using Lumina.Contracts.Requests.Themes;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.Themes;
/// <summary>
/// Contains unit tests for the <see cref="RestoreThemeRequestMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RestoreThemeRequestMappingTests
{
private readonly RestoreThemeRequestFixture _restoreThemeRequestFixture = new();
[Fact]
public void ToCommand_WhenMappingRequest_ShouldMapThemeId()
{
// Arrange
RestoreThemeRequest request = _restoreThemeRequestFixture.Create(themeId: "editorial-paper");
// Act
RestoreThemeCommand command = request.ToCommand();
// Assert
Assert.NotNull(command);
Assert.Equal(request.ThemeId, command.ThemeId);
}
}
@@ -48,6 +48,7 @@ public class ThemeEntityMappingTests
Assert.Equal(theme.InstallSource, result.InstallSource);
Assert.Equal(theme.IsCurrent, result.IsCurrent);
Assert.Equal(theme.InstalledAtUtc, result.InstalledAtUtc);
Assert.Equal(theme.IsDeleted, result.IsDeleted);
}
[Fact]
@@ -0,0 +1,241 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Themes;
using Lumina.Application.Common.DataAccess.Repositories.Themes;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Themes;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.Themes.Management.Commands.RestoreTheme;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Themes;
using Lumina.Application.Fixtures.Core.Themes.Management.Commands.RestoreTheme;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Themes;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.Themes.Management.Commands.RestoreTheme;
/// <summary>
/// Contains unit tests for the <see cref="RestoreThemeCommandHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RestoreThemeCommandHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IThemeService _mockThemeService;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly IValidator<RestoreThemeCommand> _mockValidator;
private readonly IThemeRepository _mockThemeRepository;
private readonly RestoreThemeCommandHandler _sut;
private readonly RestoreThemeCommandFixture _restoreThemeCommandFixture = new();
private readonly ThemeEntityFixture _themeEntityFixture = new();
private readonly Guid _userId;
/// <summary>
/// Initializes a new instance of the <see cref="RestoreThemeCommandHandlerTests"/> class.
/// </summary>
public RestoreThemeCommandHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockThemeService = Substitute.For<IThemeService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockValidator = Substitute.For<IValidator<RestoreThemeCommand>>();
_mockThemeRepository = Substitute.For<IThemeRepository>();
_userId = Guid.NewGuid();
_mockValidator.Validate(Arg.Any<RestoreThemeCommand>())
.Returns([]);
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>())
.Returns(true);
_mockUnitOfWork.ThemeRepository.Returns(_mockThemeRepository);
_mockThemeService.RestoreBundledThemeAsync(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(Result.Success);
_sut = new RestoreThemeCommandHandler(
_mockUnitOfWork,
_mockThemeService,
_mockCurrentUserService,
_mockAuthorizationService,
_mockValidator);
}
[Fact]
public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutAnyDownstreamCalls()
{
// Arrange
RestoreThemeCommand command = _restoreThemeCommandFixture.Create();
_mockValidator.Validate(Arg.Any<RestoreThemeCommand>())
.Returns([Errors.Themes.ThemeIdCannotBeEmpty]);
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Themes.ThemeIdCannotBeEmpty, result.FirstError);
await _mockThemeRepository.DidNotReceive().GetByThemeIdAsync(Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
RestoreThemeCommand command = _restoreThemeCommandFixture.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 _mockThemeRepository.DidNotReceive().GetByThemeIdAsync(Arg.Any<string>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAdmin_ShouldReturnNotAuthorizedError()
{
// Arrange
RestoreThemeCommand command = _restoreThemeCommandFixture.Create();
_mockAuthorizationService.IsInRoleAsync(_userId, "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 _mockThemeRepository.DidNotReceive().GetByThemeIdAsync(Arg.Any<string>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetThemeFails_ShouldReturnError()
{
// Arrange
RestoreThemeCommand command = _restoreThemeCommandFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to get theme");
_mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenThemeDoesNotExist_ShouldReturnThemeNotFoundError()
{
// Arrange
RestoreThemeCommand command = _restoreThemeCommandFixture.Create();
_mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(null));
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Themes.ThemeNotFound, result.FirstError);
await _mockThemeService.DidNotReceive().RestoreBundledThemeAsync(Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenThemeIsNotDeleted_ShouldReturnThemeCannotBeRestoredError()
{
// Arrange
RestoreThemeCommand command = _restoreThemeCommandFixture.Create();
ThemeEntity theme = _themeEntityFixture.Create(themeId: command.ThemeId, installSource: ThemeInstallSource.Bundled, isDeleted: false);
_mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(theme));
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Themes.ThemeCannotBeRestored, result.FirstError);
await _mockThemeService.DidNotReceive().RestoreBundledThemeAsync(Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenThemeIsDeletedButNotBundled_ShouldReturnThemeCannotBeRestoredError()
{
// Arrange
RestoreThemeCommand command = _restoreThemeCommandFixture.Create();
ThemeEntity theme = _themeEntityFixture.Create(themeId: command.ThemeId, installSource: ThemeInstallSource.Uploaded, isDeleted: true);
_mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(theme));
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Themes.ThemeCannotBeRestored, result.FirstError);
await _mockThemeService.DidNotReceive().RestoreBundledThemeAsync(Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenFileRestorationFails_ShouldReturnErrorWithoutReactivatingTheme()
{
// Arrange
RestoreThemeCommand command = _restoreThemeCommandFixture.Create();
ThemeEntity theme = _themeEntityFixture.Create(themeId: command.ThemeId, installSource: ThemeInstallSource.Bundled, isDeleted: true);
Error error = Error.Failure("Theme.FilesUnreadable", "Failed to restore theme files");
_mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(theme));
_mockThemeService.RestoreBundledThemeAsync(theme.ThemeId, Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenRestoringDeletedBundledTheme_ShouldRestoreFilesAndReactivateTheme()
{
// Arrange
RestoreThemeCommand command = _restoreThemeCommandFixture.Create();
ThemeEntity theme = _themeEntityFixture.Create(themeId: command.ThemeId, installSource: ThemeInstallSource.Bundled, isDeleted: true);
_mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(theme));
_mockThemeRepository.UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockThemeService.Received(1).RestoreBundledThemeAsync(theme.ThemeId, Arg.Any<CancellationToken>());
await _mockThemeRepository.Received(1).UpdateAsync(
Arg.Is<ThemeEntity>(entity => entity.Id == theme.Id && !entity.IsDeleted && entity.IsCurrent == null && entity.UpdatedBy == _userId),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,61 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Themes.Management.Commands.RestoreTheme;
using Lumina.Application.Fixtures.Core.Themes.Management.Commands.RestoreTheme;
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.Themes.Management.Commands.RestoreTheme;
/// <summary>
/// Contains unit tests for the <see cref="RestoreThemeCommandValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RestoreThemeCommandValidatorTests
{
private readonly RestoreThemeCommandValidator _validator = new();
private readonly RestoreThemeCommandFixture _restoreThemeCommandFixture = new();
[Fact]
public void Validate_WhenThemeIdIsNull_ShouldHaveValidationError()
{
// Arrange
RestoreThemeCommand command = _restoreThemeCommandFixture.Create();
command = command with { ThemeId = null };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Themes.ThemeIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenThemeIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
RestoreThemeCommand command = _restoreThemeCommandFixture.Create(themeId: string.Empty);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Themes.ThemeIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenThemeIdIsValid_ShouldNotHaveValidationErrors()
{
// Arrange
RestoreThemeCommand command = _restoreThemeCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
Assert.Empty(result);
}
}
@@ -41,7 +41,7 @@ public class GetThemesQueryHandlerTests
}
[Fact]
public async Task HandleAsync_WhenCalled_ShouldReturnAllAvailableThemesOrderedBundledFirstThenByName()
public async Task HandleAsync_WhenCalled_ShouldReturnAllThemesOrderedAvailableBundledFirstThenByNameWithDeletedLast()
{
// Arrange
GetThemesQuery query = _getThemesQueryFixture.Create();
@@ -57,13 +57,15 @@ public class GetThemesQueryHandlerTests
// Assert
Assert.False(result.IsFailure);
Assert.Equal(3, result.Value.Count);
Assert.Equal(4, result.Value.Count);
Assert.Equal(bundledLowerTheme.Id, result.Value[0].Id);
Assert.Equal(bundledUpperTheme.Id, result.Value[1].Id);
Assert.Equal(uploadedTheme.Id, result.Value[2].Id);
Assert.Equal(deletedTheme.Id, result.Value[3].Id);
Assert.Equal(ThemeInstallSource.Bundled, result.Value[0].InstallSource);
Assert.Equal(ThemeInstallSource.Bundled, result.Value[1].InstallSource);
Assert.Equal(ThemeInstallSource.Uploaded, result.Value[2].InstallSource);
Assert.True(result.Value[3].IsDeleted);
}
[Fact]
@@ -0,0 +1,202 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Core.Themes.Management.Commands.RestoreTheme;
using Lumina.Contracts.Fixtures.Core.Requests.Themes;
using Lumina.Contracts.Requests.Themes;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Core.Endpoints.Themes.Management.RestoreTheme;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Themes.Management.RestoreTheme;
/// <summary>
/// Contains unit tests for the <see cref="RestoreThemeEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RestoreThemeEndpointTests
{
private readonly Application.Common.CQRS.ICommandHandler<RestoreThemeCommand, Result<Success>> _mockHandler;
private readonly RestoreThemeEndpoint _sut;
private readonly RestoreThemeRequestFixture _restoreThemeRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="RestoreThemeEndpointTests"/> class.
/// </summary>
public RestoreThemeEndpointTests()
{
_mockHandler = Substitute.For<Application.Common.CQRS.ICommandHandler<RestoreThemeCommand, Result<Success>>>();
_sut = Factory.Create<RestoreThemeEndpoint>(_mockHandler);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnNoContentResult()
{
// Arrange
RestoreThemeRequest request = _restoreThemeRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<RestoreThemeCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Success));
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
Assert.IsType<NoContent>(result);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult()
{
// Arrange
RestoreThemeRequest request = _restoreThemeRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = DomainErrors.Themes.ThemeNotFound;
_mockHandler.HandleAsync(Arg.Any<RestoreThemeCommand>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status404NotFound, 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.Status404NotFound, problemDetailsBody.Status);
Assert.Equal("General.NotFound", problemDetailsBody.Title);
Assert.Equal("ThemeNotFound", problemDetailsBody.Detail);
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetailsBody.Type);
Assert.NotNull(problemDetailsBody.Extensions["traceId"]);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult()
{
// Arrange
RestoreThemeRequest request = _restoreThemeRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = ApplicationErrors.Authorization.NotAuthorized;
_mockHandler.HandleAsync(Arg.Any<RestoreThemeCommand>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
IResult result = await _sut.ExecuteAsync(request, 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_WhenHandlerReturnsForbiddenError_ShouldReturnProblemResult()
{
// Arrange
RestoreThemeRequest request = _restoreThemeRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = DomainErrors.Themes.ThemeCannotBeRestored;
_mockHandler.HandleAsync(Arg.Any<RestoreThemeCommand>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
IResult result = await _sut.ExecuteAsync(request, 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.Forbidden", problemDetailsBody.Title);
Assert.Equal("ThemeCannotBeRestored", 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_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult()
{
// Arrange
RestoreThemeRequest request = _restoreThemeRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = DomainErrors.Themes.ThemeIdCannotBeEmpty;
_mockHandler.HandleAsync(Arg.Any<RestoreThemeCommand>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
HttpValidationProblemDetails validationProblemDetails = Assert.IsType<HttpValidationProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status);
Assert.Equal("General.Validation", validationProblemDetails.Title);
Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail);
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type);
Assert.Single(validationProblemDetails.Errors);
Assert.Equal(new[] { "ThemeIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]);
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldSendRestoreThemeCommandToHandler()
{
// Arrange
RestoreThemeRequest request = _restoreThemeRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<RestoreThemeCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Success));
// Act
await _sut.ExecuteAsync(request, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<RestoreThemeCommand>(command => command.ThemeId == request.ThemeId),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
RestoreThemeRequest request = _restoreThemeRequestFixture.Create();
CancellationTokenSource cts = new();
TaskCompletionSource<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
_mockHandler.HandleAsync(Arg.Any<RestoreThemeCommand>(), 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>()));
// Act
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
await operationStarted.Task;
cts.Cancel();
cancellationRequested.SetResult(true);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
}
}
@@ -0,0 +1,85 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.Themes;
using Lumina.Presentation.Web.Common.Requests.Themes;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.RestoreTheme;
using Lumina.Presentation.Web.Core.Themes;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
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.Web.UnitTests.Core.Endpoints.Admin.Themes.RestoreTheme;
/// <summary>
/// Contains unit tests for the <see cref="RestoreThemeEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RestoreThemeEndpointTests
{
private readonly IApiHttpClient _mockApiHttpClient;
private readonly RestoreThemeEndpoint _sut;
/// <summary>
/// Initializes a new instance of the <see cref="RestoreThemeEndpointTests"/> class.
/// </summary>
public RestoreThemeEndpointTests()
{
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
ThemeService themeService = new(_mockApiHttpClient);
_sut = Factory.Create<RestoreThemeEndpoint>(themeService);
}
[Fact]
public async Task ExecuteAsync_WhenThemeIdProvided_ShouldRestoreThemeAndReturnSuccessJson()
{
// Arrange
string themeId = "editorial-paper";
// Act
IResult result = await _sut.ExecuteAsync(new RestoreThemeRequest(themeId), CancellationToken.None);
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
// Assert
using (System.Text.Json.JsonDocument jsonDocument = System.Text.Json.JsonDocument.Parse(body))
{
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
}
}
[Fact]
public async Task ExecuteAsync_WhenThemeIdProvided_ShouldRestoreThemeWithResolvedEndpoint()
{
// Arrange
string themeId = "editorial-paper";
string expectedEndpoint = ApiRoutes.Themes.RESTORE_THEME.Replace("{themeId}", themeId);
// Act
await _sut.ExecuteAsync(new RestoreThemeRequest(themeId), CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).PostAsync<ThemeResponseDto, object>(expectedEndpoint, Arg.Any<object>(), Arg.Any<CancellationToken>());
}
[Theory]
[InlineData(null)] // missing theme id
[InlineData("")] // empty theme id
[InlineData(" ")] // whitespace theme id
public async Task ExecuteAsync_WhenThemeIdIsBlank_ShouldReturnProblemWithBadRequest(string? themeId)
{
// Act
IResult result = await _sut.ExecuteAsync(new RestoreThemeRequest(themeId), CancellationToken.None);
// Assert
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status400BadRequest, problemResult.StatusCode);
await _mockApiHttpClient.DidNotReceive().PostAsync<ThemeResponseDto, object>(Arg.Any<string>(), Arg.Any<object>(), Arg.Any<CancellationToken>());
}
}