mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 11:11:10 +00:00
Adds a restore action for soft deleted bundled themes
This commit is contained in:
1 parent
15945c2e56
commit
7e54c990ad
49 files changed
+1666
-26
No files matched your search
+38
@@ -0,0 +1,38 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Core.Themes.Management.Commands.RestoreTheme;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Fixtures.Core.Themes.Management.Commands.RestoreTheme;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="RestoreThemeCommand"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RestoreThemeCommandFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="RestoreThemeCommand"/>.
|
||||
/// </summary>
|
||||
/// <param name="themeId">Optional manifest id of the theme to restore.</param>
|
||||
/// <returns>The created <see cref="RestoreThemeCommand"/>.</returns>
|
||||
public RestoreThemeCommand Create(string? themeId = null)
|
||||
{
|
||||
return new RestoreThemeCommand(themeId ?? _faker.Lorem.Slug(2));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="RestoreThemeCommand"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<RestoreThemeCommand> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.Requests.Themes;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Fixtures.Core.Requests.Themes;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="RestoreThemeRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RestoreThemeRequestFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="RestoreThemeRequest"/>.
|
||||
/// </summary>
|
||||
/// <param name="themeId">Optional. The manifest id of the theme to restore.</param>
|
||||
/// <returns>The created <see cref="RestoreThemeRequest"/>.</returns>
|
||||
public RestoreThemeRequest Create(string? themeId = null)
|
||||
{
|
||||
return new RestoreThemeRequest(themeId ?? _faker.Lorem.Slug(2));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="RestoreThemeRequest"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<RestoreThemeRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+5
-2
@@ -33,6 +33,7 @@ public class ThemeResponseFixture
|
||||
/// <param name="isCurrent">Optional. Whether the theme is the currently active one.</param>
|
||||
/// <param name="includeIsCurrent">Whether to set <paramref name="isCurrent"/>, or <see langword="null"/> when <see langword="false"/>.</param>
|
||||
/// <param name="installedAtUtc">Optional. The UTC timestamp when the theme was installed.</param>
|
||||
/// <param name="isDeleted">Optional. Whether the theme was deleted by the user.</param>
|
||||
/// <returns>The created <see cref="ThemeResponse"/>.</returns>
|
||||
public ThemeResponse Create(
|
||||
Guid? id = null,
|
||||
@@ -46,7 +47,8 @@ public class ThemeResponseFixture
|
||||
ThemeInstallSource? installSource = null,
|
||||
bool? isCurrent = null,
|
||||
bool includeIsCurrent = false,
|
||||
DateTime? installedAtUtc = null)
|
||||
DateTime? installedAtUtc = null,
|
||||
bool? isDeleted = null)
|
||||
{
|
||||
return new ThemeResponse(
|
||||
id ?? Guid.NewGuid(),
|
||||
@@ -58,7 +60,8 @@ public class ThemeResponseFixture
|
||||
includePreviewPath ? (previewPath ?? (_faker.Random.Bool() ? _faker.System.FilePath() : null)) : null,
|
||||
installSource ?? _faker.PickRandom<ThemeInstallSource>(),
|
||||
includeIsCurrent ? (isCurrent ?? (_faker.Random.Bool() ? true : null)) : null,
|
||||
installedAtUtc ?? _faker.Date.Recent().ToUniversalTime());
|
||||
installedAtUtc ?? _faker.Date.Recent().ToUniversalTime(),
|
||||
isDeleted ?? _faker.Random.Bool());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
+5
-2
@@ -25,6 +25,7 @@ public class ThemeInfoDtoFixture
|
||||
/// <param name="version">Optional semantic version of the theme.</param>
|
||||
/// <param name="previewUrl">Optional URL of the theme preview image.</param>
|
||||
/// <param name="isBundled">Whether the theme ships with the application.</param>
|
||||
/// <param name="isDeleted">Whether the theme was deleted by the user.</param>
|
||||
/// <returns>A configured <see cref="ThemeInfoDto"/> instance.</returns>
|
||||
public ThemeInfoDto Create(
|
||||
string? id = null,
|
||||
@@ -33,7 +34,8 @@ public class ThemeInfoDtoFixture
|
||||
string? author = null,
|
||||
string? version = null,
|
||||
string? previewUrl = null,
|
||||
bool? isBundled = null)
|
||||
bool? isBundled = null,
|
||||
bool? isDeleted = null)
|
||||
{
|
||||
Faker faker = new();
|
||||
return new ThemeInfoDto(
|
||||
@@ -43,7 +45,8 @@ public class ThemeInfoDtoFixture
|
||||
Author: author ?? faker.Name.FullName(),
|
||||
Version: version ?? faker.System.Semver(),
|
||||
PreviewUrl: previewUrl ?? $"/theme-assets/{faker.Lorem.Word()}/preview.png",
|
||||
IsBundled: isBundled ?? faker.Random.Bool()
|
||||
IsBundled: isBundled ?? faker.Random.Bool(),
|
||||
IsDeleted: isDeleted ?? faker.Random.Bool()
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
+5
-2
@@ -31,6 +31,7 @@ public class ThemeResponseDtoFixture
|
||||
/// <param name="isCurrent">Optional value indicating whether the theme is the active one.</param>
|
||||
/// <param name="includeIsCurrent">Whether to set <paramref name="isCurrent"/>, or <see langword="null"/> when <see langword="false"/>.</param>
|
||||
/// <param name="installedAtUtc">Optional UTC timestamp at which the theme was installed.</param>
|
||||
/// <param name="isDeleted">Optional value indicating whether the theme was deleted by the user.</param>
|
||||
/// <returns>A configured <see cref="ThemeResponseDto"/> instance.</returns>
|
||||
public ThemeResponseDto Create(
|
||||
Guid? id = null,
|
||||
@@ -44,7 +45,8 @@ public class ThemeResponseDtoFixture
|
||||
ThemeInstallSource? installSource = null,
|
||||
bool? isCurrent = null,
|
||||
bool includeIsCurrent = false,
|
||||
DateTime? installedAtUtc = null)
|
||||
DateTime? installedAtUtc = null,
|
||||
bool? isDeleted = null)
|
||||
{
|
||||
Faker faker = new();
|
||||
return new ThemeResponseDto(
|
||||
@@ -57,7 +59,8 @@ public class ThemeResponseDtoFixture
|
||||
PreviewPath: includePreviewPath ? (previewPath ?? (faker.Random.Bool() ? faker.System.FilePath() : null)) : null,
|
||||
InstallSource: installSource ?? ThemeInstallSource.Uploaded,
|
||||
IsCurrent: includeIsCurrent ? (isCurrent ?? (faker.Random.Bool() ? true : null)) : null,
|
||||
InstalledAtUtc: installedAtUtc ?? faker.Date.Recent()
|
||||
InstalledAtUtc: installedAtUtc ?? faker.Date.Recent(),
|
||||
IsDeleted: isDeleted ?? faker.Random.Bool()
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
+231
@@ -0,0 +1,231 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Themes;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.Infrastructure.Themes;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Themes.Management.RestoreTheme;
|
||||
using Lumina.Presentation.Api.Fixtures.Core.Endpoints.Themes;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Themes.Management.RestoreTheme;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="RestoreThemeEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RestoreThemeEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly TestThemeArchiveFixture _themeArchiveFixture = new();
|
||||
private readonly List<string> _installedThemeIds = [];
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RestoreThemeEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public RestoreThemeEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes an authenticated admin API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedAdminClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RestoreTheme_WhenCalledWithDeletedBundledTheme_ShouldRestoreTheme()
|
||||
{
|
||||
// Arrange
|
||||
await ThemeTestHelpers.WaitForBundledThemeAsync(_apiFactory);
|
||||
using (IServiceScope scope = _apiFactory.Services.CreateScope())
|
||||
{
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
ThemeEntity? theme = await dbContext.Themes.FirstOrDefaultAsync(candidate => candidate.ThemeId == "editorial-paper");
|
||||
Assert.NotNull(theme);
|
||||
theme!.IsDeleted = true;
|
||||
theme.IsCurrent = null;
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/themes/editorial-paper/restore", new { });
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NoContent, response.StatusCode);
|
||||
|
||||
// the theme is available again and appears in the list
|
||||
using IServiceScope verificationScope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext verificationContext = verificationScope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
ThemeEntity? restoredTheme = await verificationContext.Themes.FirstOrDefaultAsync(candidate => candidate.ThemeId == "editorial-paper");
|
||||
Assert.NotNull(restoredTheme);
|
||||
Assert.False(restoredTheme!.IsDeleted);
|
||||
|
||||
HttpResponseMessage listResponse = await _client.GetAsync("/api/v1/themes");
|
||||
List<Lumina.Contracts.Responses.Themes.ThemeResponse>? themes = await listResponse.Content.ReadFromJsonAsync<List<Lumina.Contracts.Responses.Themes.ThemeResponse>>(_jsonOptions);
|
||||
Assert.NotNull(themes);
|
||||
Assert.Contains(themes!, theme => theme.ThemeId == "editorial-paper" && !theme.IsDeleted);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RestoreTheme_WhenThemeDoesNotExist_ShouldReturnNotFound()
|
||||
{
|
||||
// Arrange
|
||||
string themeId = "nonexistent-theme";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/themes/{themeId}/restore", new { });
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.NotFound", problemDetails["title"].GetString());
|
||||
Assert.Equal("ThemeNotFound", problemDetails["detail"].GetString());
|
||||
Assert.Equal($"/api/v1/themes/{themeId}/restore", problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RestoreTheme_WhenThemeIsNotDeleted_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
string themeId = await InstallUserThemeAsync();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/themes/{themeId}/restore", new { });
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Forbidden", problemDetails["title"].GetString());
|
||||
Assert.Equal("ThemeCannotBeRestored", problemDetails["detail"].GetString());
|
||||
Assert.Equal($"/api/v1/themes/{themeId}/restore", problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RestoreTheme_WhenCalledWithNonAdminAccount_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient nonAdminClient = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await nonAdminClient.PostAsJsonAsync("/api/v1/themes/editorial-paper/restore", new { });
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
|
||||
Assert.Equal("/api/v1/themes/editorial-paper/restore", problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RestoreTheme_WhenCalledWithoutAuthentication_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient anonymousClient = _apiFactory.CreateClient();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.PostAsJsonAsync("/api/v1/themes/editorial-paper/restore", new { });
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Installs a test theme through the API and returns its manifest id.
|
||||
/// </summary>
|
||||
/// <returns>The manifest id of the installed theme.</returns>
|
||||
private async Task<string> InstallUserThemeAsync()
|
||||
{
|
||||
string themeId = $"test-theme-{Guid.NewGuid():N}";
|
||||
byte[] archiveBytes = _themeArchiveFixture.Create(themeId);
|
||||
|
||||
using MultipartFormDataContent multipartContent = [];
|
||||
using ByteArrayContent fileContent = new(archiveBytes);
|
||||
multipartContent.Add(fileContent, "file", "theme.zip");
|
||||
|
||||
HttpResponseMessage response = await _client.PostAsync("/api/v1/themes", multipartContent);
|
||||
response.EnsureSuccessStatusCode();
|
||||
|
||||
_installedThemeIds.Add(themeId);
|
||||
return themeId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes any test theme installed by a failed test and clears the authorization seed data of the admin test user.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
foreach (string themeId in _installedThemeIds)
|
||||
{
|
||||
ThemeEntity? theme = await dbContext.Themes.FirstOrDefaultAsync(t => t.ThemeId == themeId);
|
||||
if (theme is not null)
|
||||
dbContext.Themes.Remove(theme);
|
||||
}
|
||||
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
IThemeService themeService = scope.ServiceProvider.GetRequiredService<IThemeService>();
|
||||
foreach (string themeId in _installedThemeIds)
|
||||
await themeService.DeleteAsync(themeId, CancellationToken.None);
|
||||
|
||||
// the admin seeding performed by the factory is not idempotent, so the seed data must be cleared between tests
|
||||
await dbContext.Set<RolePermissionEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<UserPermissionEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<UserRoleEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<UserEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<RoleEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<PermissionEntity>().ExecuteDeleteAsync();
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+193
@@ -0,0 +1,193 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Themes;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Themes;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Themes.Management.RestoreTheme;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <c>POST /api/v1/themes/{themeId}/restore</c> route.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RestoreThemeEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
{
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly HttpClient _client;
|
||||
private readonly string _themeId;
|
||||
private readonly ThemeEntityFixture _themeEntityFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RestoreThemeEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public RestoreThemeEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
// a unique X-Forwarded-For isolates rate limiting state per test
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
|
||||
_themeId = $"testtheme{Guid.NewGuid():N}";
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RestoreTheme_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/themes/{Guid.NewGuid():N}/restore";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(url, new { });
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal(url, problemDetails["instance"].GetProperty("value").GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RestoreTheme_WhenAuthenticatedNonAdmin_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
string url = $"/api/v1/themes/{Guid.NewGuid():N}/restore";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PostAsJsonAsync(url, new { });
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
|
||||
Assert.Equal(url, problemDetails["instance"].GetString());
|
||||
Assert.True(problemDetails.ContainsKey("traceId"));
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RestoreTheme_WhenThemeIsNotDeleted_ShouldReturnForbiddenResultWithoutReactivatingIt()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
|
||||
await SeedThemeAsync(isDeleted: false);
|
||||
string url = $"/api/v1/themes/{_themeId}/restore";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PostAsJsonAsync(url, new { });
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Forbidden", problemDetails["title"].GetString());
|
||||
Assert.Equal("ThemeCannotBeRestored", problemDetails["detail"].GetString());
|
||||
Assert.Equal(url, problemDetails["instance"].GetString());
|
||||
Assert.True(problemDetails.ContainsKey("traceId"));
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("..%2F..%2Fevil")] // encoded slash traversal
|
||||
[InlineData("%2e%2e%2f%2e%2e%2fevil")] // encoded dot-slash traversal
|
||||
[InlineData("..%5Cevil")] // encoded backslash traversal
|
||||
[InlineData("..%2F")] // encoded trailing slash traversal
|
||||
public async Task RestoreTheme_WithPathTraversalInThemeId_ShouldReturnCleanNotFoundProblemDetails(string maliciousThemeId)
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
|
||||
string url = $"/api/v1/themes/{maliciousThemeId}/restore";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PostAsJsonAsync(url, new { });
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
// note: some payloads are normalized away by the server before routing, producing an empty-body 404;
|
||||
// when the value reaches the handler, the failure must still be the generic theme-not-found problem
|
||||
if (!string.IsNullOrWhiteSpace(content))
|
||||
{
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.NotFound", problemDetails["title"].GetString());
|
||||
Assert.Equal("ThemeNotFound", problemDetails["detail"].GetString());
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a <see cref="ThemeEntity"/> with the unique test theme id.
|
||||
/// </summary>
|
||||
/// <param name="isDeleted">Whether the seeded theme is marked as deleted.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task SeedThemeAsync(bool isDeleted)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Themes.Add(_themeEntityFixture.Create(themeId: _themeId, isDeleted: isDeleted));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the seeded theme.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
ThemeEntity? theme = dbContext.Themes.FirstOrDefault(candidate => candidate.ThemeId == _themeId);
|
||||
if (theme is not null)
|
||||
{
|
||||
dbContext.Themes.Remove(theme);
|
||||
dbContext.SaveChanges();
|
||||
}
|
||||
|
||||
_client.Dispose();
|
||||
}
|
||||
}
|
||||
+32
@@ -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);
|
||||
}
|
||||
}
|
||||
+1
@@ -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]
|
||||
|
||||
+241
@@ -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>());
|
||||
}
|
||||
}
|
||||
+61
@@ -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);
|
||||
}
|
||||
}
|
||||
+4
-2
@@ -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]
|
||||
|
||||
+202
@@ -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);
|
||||
}
|
||||
}
|
||||
+85
@@ -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>());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user