Adds the integration tests for the theming feature

This commit is contained in:
BinaryAlley committed 2026-08-21 09:43:19 -07:00
1 parent baa6450406
commit 02f27655f8
10 files changed
+1385

No files matched your search

@@ -0,0 +1,42 @@
#region ========================================================================= USING =====================================================================================
using Lumina.DataAccess.Core.UoW;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Common.Setup;
/// <summary>
/// Helpers shared by the theme integration tests.
/// </summary>
[ExcludeFromCodeCoverage]
public static class ThemeTestHelpers
{
/// <summary>
/// Waits until the bundled 'editorial-paper' theme has been installed and activated by the theme detection job at startup.
/// </summary>
/// <param name="apiFactory">The shared API factory whose database is polled.</param>
/// <returns>A task representing the asynchronous operation.</returns>
public static async Task WaitForBundledThemeAsync(AuthenticatedLuminaApiFactory apiFactory)
{
const int MAX_ATTEMPTS = 100;
const int DELAY_MILLISECONDS = 100;
for (int attempt = 0; attempt < MAX_ATTEMPTS; attempt++)
{
using IServiceScope scope = apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
if (await dbContext.Themes.AnyAsync(theme => theme.ThemeId == "editorial-paper" && theme.IsCurrent == true))
return;
await Task.Delay(DELAY_MILLISECONDS);
}
Assert.Fail("The bundled theme 'editorial-paper' was not installed and activated within the expected time.");
}
}
@@ -0,0 +1,223 @@
#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.Contracts.Responses.Themes;
using Lumina.DataAccess.Core.UoW;
using Lumina.Presentation.Api.Core.Endpoints.Themes.Management.DeleteTheme;
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.Linq;
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.DeleteTheme;
/// <summary>
/// Contains integration tests for the <see cref="DeleteThemeEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeleteThemeEndpointTests : 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="DeleteThemeEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public DeleteThemeEndpointTests(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 DeleteTheme_WhenCalledWithExistingTheme_ShouldDeleteTheme()
{
// Arrange
string themeId = await InstallThemeAsync();
// Act
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/themes/{themeId}");
// Assert
Assert.Equal(HttpStatusCode.NoContent, response.StatusCode);
// the theme row is removed from the database
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.Null(await dbContext.Themes.FirstOrDefaultAsync(theme => theme.ThemeId == themeId));
// the theme no longer appears in GET /themes
HttpResponseMessage listResponse = await _client.GetAsync("/api/v1/themes");
List<ThemeResponse>? themes = await listResponse.Content.ReadFromJsonAsync<List<ThemeResponse>>(_jsonOptions);
Assert.NotNull(themes);
Assert.DoesNotContain(themes!, theme => theme.ThemeId == themeId);
}
[Fact]
public async Task DeleteTheme_WhenThemeDoesNotExist_ShouldReturnNotFound()
{
// Arrange
string themeId = "nonexistent-theme";
// Act
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/themes/{themeId}");
// 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}", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
}
[Fact]
public async Task DeleteTheme_WhenTryingToDeleteTheLastBundledTheme_ShouldReturnForbiddenResult()
{
// Arrange
await ThemeTestHelpers.WaitForBundledThemeAsync(_apiFactory);
// Act
HttpResponseMessage response = await _client.DeleteAsync("/api/v1/themes/editorial-paper");
// 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("LastBundledThemeCannotBeDeleted", problemDetails["detail"].GetString());
Assert.Equal("/api/v1/themes/editorial-paper", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
}
[Fact]
public async Task DeleteTheme_WhenCalledWithNonAdminAccount_ShouldReturnForbiddenResult()
{
// Arrange
HttpClient nonAdminClient = await _apiFactory.CreateAuthenticatedClientAsync();
// Act
HttpResponseMessage response = await nonAdminClient.DeleteAsync("/api/v1/themes/editorial-paper");
// 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", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
}
[Fact]
public async Task DeleteTheme_WhenCalledWithoutAuthentication_ShouldReturnUnauthorizedResult()
{
// Arrange
HttpClient anonymousClient = _apiFactory.CreateClient();
// Act
HttpResponseMessage response = await anonymousClient.DeleteAsync("/api/v1/themes/editorial-paper");
// 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> InstallThemeAsync()
{
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>
/// Disposes API factory resources, removing any test theme left installed by a failed deletion and clearing 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();
}
}
@@ -0,0 +1,237 @@
#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.Contracts.Responses.Themes;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.Themes;
using Lumina.Presentation.Api.Core.Endpoints.Themes.Management.InstallTheme;
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.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text;
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.InstallTheme;
/// <summary>
/// Contains integration tests for the <see cref="InstallThemeEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class InstallThemeEndpointTests : 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="InstallThemeEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public InstallThemeEndpointTests(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 InstallTheme_WhenCalledWithValidArchive_ShouldInstallTheme()
{
// Arrange
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");
// Act
HttpResponseMessage response = await _client.PostAsync("/api/v1/themes", multipartContent);
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
ThemeResponse? result = await response.Content.ReadFromJsonAsync<ThemeResponse>(_jsonOptions);
Assert.NotNull(result);
Assert.Equal(themeId, result!.ThemeId);
Assert.Equal("Test Theme", result.Name);
Assert.Equal(ThemeInstallSource.Uploaded, result.InstallSource);
Assert.Null(result.IsCurrent);
// the installed theme is listed by GET /themes
HttpResponseMessage listResponse = await _client.GetAsync("/api/v1/themes");
List<ThemeResponse>? themes = await listResponse.Content.ReadFromJsonAsync<List<ThemeResponse>>(_jsonOptions);
Assert.NotNull(themes);
Assert.Contains(themes!, theme => theme.ThemeId == themeId);
// the installed theme is persisted in the database
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.NotNull(await dbContext.Themes.FirstOrDefaultAsync(theme => theme.ThemeId == themeId));
_installedThemeIds.Add(themeId);
}
[Fact]
public async Task InstallTheme_WhenCalledWithInvalidArchive_ShouldReturnProblemResult()
{
// Arrange
byte[] invalidArchive = Encoding.UTF8.GetBytes("this is not a valid zip archive");
using MultipartFormDataContent multipartContent = [];
using ByteArrayContent fileContent = new(invalidArchive);
multipartContent.Add(fileContent, "file", "theme.zip");
// Act
HttpResponseMessage response = await _client.PostAsync("/api/v1/themes", multipartContent);
// 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.Failure", problemDetails["title"].GetString());
Assert.Equal("ThemeArchiveNotReadable", problemDetails["detail"].GetString());
Assert.Equal("/api/v1/themes", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
}
[Fact]
public async Task InstallTheme_WhenCalledWithoutArchive_ShouldReturnValidationProblem()
{
// Arrange
// a multipart form without any file part, only a regular form field, so the archive is missing
using MultipartFormDataContent multipartContent = [];
multipartContent.Add(new StringContent("value"), "field");
// Act
HttpResponseMessage response = await _client.PostAsync("/api/v1/themes", multipartContent);
// Assert
Assert.Equal(HttpStatusCode.UnprocessableContent, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors.Keys);
Assert.Contains("ThemeArchiveCannotBeNull", errors["General.Validation"]);
}
[Fact]
public async Task InstallTheme_WhenCalledWithNonAdminAccount_ShouldReturnForbiddenResult()
{
// Arrange
HttpClient nonAdminClient = await _apiFactory.CreateAuthenticatedClientAsync();
byte[] archiveBytes = _themeArchiveFixture.Create();
using MultipartFormDataContent multipartContent = [];
using ByteArrayContent fileContent = new(archiveBytes);
multipartContent.Add(fileContent, "file", "theme.zip");
// Act
HttpResponseMessage response = await nonAdminClient.PostAsync("/api/v1/themes", multipartContent);
// 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", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
}
[Fact]
public async Task InstallTheme_WhenCalledWithoutAuthentication_ShouldReturnUnauthorizedResult()
{
// Arrange
HttpClient anonymousClient = _apiFactory.CreateClient();
byte[] archiveBytes = _themeArchiveFixture.Create();
using MultipartFormDataContent multipartContent = [];
using ByteArrayContent fileContent = new(archiveBytes);
multipartContent.Add(fileContent, "file", "theme.zip");
// Act
HttpResponseMessage response = await anonymousClient.PostAsync("/api/v1/themes", multipartContent);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
/// <summary>
/// Disposes API factory resources, removing the installed test themes and 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();
}
}
@@ -0,0 +1,244 @@
#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.Contracts.Requests.Themes;
using Lumina.Contracts.Responses.Themes;
using Lumina.DataAccess.Core.UoW;
using Lumina.Presentation.Api.Core.Endpoints.Themes.Management.SetCurrentTheme;
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.SetCurrentTheme;
/// <summary>
/// Contains integration tests for the <see cref="SetCurrentThemeEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetCurrentThemeEndpointTests : 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="SetCurrentThemeEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public SetCurrentThemeEndpointTests(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 SetCurrentTheme_WhenCalledWithExistingTheme_ShouldSetCurrentTheme()
{
// Arrange
await ThemeTestHelpers.WaitForBundledThemeAsync(_apiFactory);
string themeId = await InstallThemeAsync();
SetCurrentThemeRequest request = new(ThemeId: themeId);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/themes/current", request);
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
ThemeResponse? result = await response.Content.ReadFromJsonAsync<ThemeResponse>(_jsonOptions);
Assert.NotNull(result);
Assert.Equal(themeId, result!.ThemeId);
Assert.True(result.IsCurrent);
// the newly active theme is returned by GET /themes/current
HttpResponseMessage currentResponse = await _client.GetAsync("/api/v1/themes/current");
ThemeResponse? current = await currentResponse.Content.ReadFromJsonAsync<ThemeResponse>(_jsonOptions);
Assert.NotNull(current);
Assert.Equal(themeId, current!.ThemeId);
Assert.True(current.IsCurrent);
}
[Fact]
public async Task SetCurrentTheme_WhenThemeDoesNotExist_ShouldReturnNotFound()
{
// Arrange
string themeId = "nonexistent-theme";
SetCurrentThemeRequest request = new(ThemeId: themeId);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/themes/current", request);
// 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/current", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
}
[Fact]
public async Task SetCurrentTheme_WhenThemeIdIsEmpty_ShouldReturnValidationProblem()
{
// Arrange
SetCurrentThemeRequest request = new(ThemeId: string.Empty);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/themes/current", request);
// Assert
Assert.Equal(HttpStatusCode.UnprocessableContent, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors.Keys);
Assert.Contains("ThemeIdCannotBeEmpty", errors["General.Validation"]);
}
[Fact]
public async Task SetCurrentTheme_WhenCalledWithNonAdminAccount_ShouldReturnForbiddenResult()
{
// Arrange
HttpClient nonAdminClient = await _apiFactory.CreateAuthenticatedClientAsync();
SetCurrentThemeRequest request = new(ThemeId: "editorial-paper");
// Act
HttpResponseMessage response = await nonAdminClient.PutAsJsonAsync("/api/v1/themes/current", request);
// 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/current", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
}
[Fact]
public async Task SetCurrentTheme_WhenCalledWithoutAuthentication_ShouldReturnUnauthorizedResult()
{
// Arrange
HttpClient anonymousClient = _apiFactory.CreateClient();
SetCurrentThemeRequest request = new(ThemeId: "editorial-paper");
// Act
HttpResponseMessage response = await anonymousClient.PutAsJsonAsync("/api/v1/themes/current", request);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
/// <summary>
/// Installs a test theme through the API and returns its manifest id.
/// </summary>
/// <param name="themeId">Optional manifest id of the theme to install.</param>
/// <returns>The manifest id of the installed theme.</returns>
private async Task<string> InstallThemeAsync(string? themeId = null)
{
string resolvedThemeId = themeId ?? $"test-theme-{Guid.NewGuid():N}";
byte[] archiveBytes = _themeArchiveFixture.Create(resolvedThemeId);
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(resolvedThemeId);
return resolvedThemeId;
}
/// <summary>
/// Disposes API factory resources, removing the installed test themes, restoring the bundled theme as the active one, and clearing 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)
{
theme.IsCurrent = null;
dbContext.Themes.Remove(theme);
}
}
// restore the bundled theme as the active one, so the following tests start from a clean state
ThemeEntity? bundledTheme = await dbContext.Themes.FirstOrDefaultAsync(t => t.ThemeId == "editorial-paper");
if (bundledTheme is not null)
bundledTheme.IsCurrent = true;
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();
}
}
@@ -0,0 +1,88 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Responses.Themes;
using Lumina.Presentation.Api.Core.Endpoints.Themes.Queries.GetCurrentTheme;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
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.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Themes.Queries.GetCurrentTheme;
/// <summary>
/// Contains integration tests for the <see cref="GetCurrentThemeEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetCurrentThemeEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private HttpClient _client;
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
/// <summary>
/// Initializes a new instance of the <see cref="GetCurrentThemeEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetCurrentThemeEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Fact]
public async Task GetCurrentTheme_WhenCalled_ShouldReturnTheCurrentTheme()
{
// Arrange
await ThemeTestHelpers.WaitForBundledThemeAsync(_apiFactory);
// Act
HttpResponseMessage response = await _client.GetAsync("/api/v1/themes/current");
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
ThemeResponse? theme = await response.Content.ReadFromJsonAsync<ThemeResponse>(_jsonOptions);
Assert.NotNull(theme);
Assert.Equal("editorial-paper", theme!.ThemeId);
Assert.True(theme.IsCurrent);
}
[Fact]
public async Task GetCurrentTheme_WhenCalledWithoutAuthentication_ShouldReturnTheCurrentTheme()
{
// Arrange
await ThemeTestHelpers.WaitForBundledThemeAsync(_apiFactory);
HttpClient anonymousClient = _apiFactory.CreateClient();
// Act
HttpResponseMessage response = await anonymousClient.GetAsync("/api/v1/themes/current");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
await _apiFactory.RemoveTestUserAsync();
}
}
@@ -0,0 +1,111 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Api.Core.Endpoints.Themes.Queries.GetThemeArchive;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Themes.Queries.GetThemeArchive;
/// <summary>
/// Contains integration tests for the <see cref="GetThemeArchiveEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetThemeArchiveEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private HttpClient _client;
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
/// <summary>
/// Initializes a new instance of the <see cref="GetThemeArchiveEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetThemeArchiveEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Fact]
public async Task GetThemeArchive_WhenCalledWithExistingTheme_ShouldReturnArchiveFile()
{
// Arrange
await ThemeTestHelpers.WaitForBundledThemeAsync(_apiFactory);
// Act
HttpResponseMessage response = await _client.GetAsync("/api/v1/themes/editorial-paper/archive");
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("application/zip", response.Content.Headers.ContentType?.MediaType);
Assert.Equal("editorial-paper.zip", response.Content.Headers.ContentDisposition?.FileName);
byte[] bytes = await response.Content.ReadAsByteArrayAsync();
Assert.NotEmpty(bytes);
}
[Fact]
public async Task GetThemeArchive_WhenThemeDoesNotExist_ShouldReturnNotFound()
{
// Arrange
string themeId = "nonexistent-theme";
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/themes/{themeId}/archive");
// 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}/archive", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
}
[Fact]
public async Task GetThemeArchive_WhenCalledWithoutAuthentication_ShouldReturnUnauthorizedResult()
{
// Arrange
HttpClient anonymousClient = _apiFactory.CreateClient();
// Act
HttpResponseMessage response = await anonymousClient.GetAsync("/api/v1/themes/editorial-paper/archive");
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
await _apiFactory.RemoveTestUserAsync();
}
}
@@ -0,0 +1,130 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Api.Core.Endpoints.Themes.Queries.GetThemeAsset;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Themes.Queries.GetThemeAsset;
/// <summary>
/// Contains integration tests for the <see cref="GetThemeAssetEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetThemeAssetEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
/// <summary>
/// Initializes a new instance of the <see cref="GetThemeAssetEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetThemeAssetEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
}
/// <summary>
/// Performs no setup; the asset endpoint is accessed anonymously.
/// </summary>
/// <returns>A task representing the asynchronous operation.</returns>
public Task InitializeAsync()
{
return Task.CompletedTask;
}
[Fact]
public async Task GetThemeAsset_WhenCalledWithExistingThemeAndAsset_ShouldReturnAssetFile()
{
// Arrange
await ThemeTestHelpers.WaitForBundledThemeAsync(_apiFactory);
HttpClient anonymousClient = _apiFactory.CreateClient();
// Act
// the asset path is relative to the theme pack root and includes the assets/ prefix, so the URL is
// /themes/{themeId}/assets/assets/{assetPath} (the first assets/ segment is the route prefix)
HttpResponseMessage response = await anonymousClient.GetAsync("/api/v1/themes/editorial-paper/assets/assets/theme.css");
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("text/css", response.Content.Headers.ContentType?.MediaType);
byte[] bytes = await response.Content.ReadAsByteArrayAsync();
Assert.NotEmpty(bytes);
}
[Fact]
public async Task GetThemeAsset_WhenThemeDoesNotExist_ShouldReturnNotFound()
{
// Arrange
HttpClient anonymousClient = _apiFactory.CreateClient();
string themeId = "nonexistent-theme";
// Act
HttpResponseMessage response = await anonymousClient.GetAsync($"/api/v1/themes/{themeId}/assets/theme.css");
// 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}/assets/theme.css", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
}
[Fact]
public async Task GetThemeAsset_WhenAssetPathIsEmpty_ShouldReturnValidationProblem()
{
// Arrange
await ThemeTestHelpers.WaitForBundledThemeAsync(_apiFactory);
HttpClient anonymousClient = _apiFactory.CreateClient();
// Act
HttpResponseMessage response = await anonymousClient.GetAsync("/api/v1/themes/editorial-paper/assets/");
// Assert
Assert.Equal(HttpStatusCode.UnprocessableContent, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors.Keys);
Assert.Contains("ThemeAssetPathCannotBeEmpty", errors["General.Validation"]);
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
await _apiFactory.RemoveTestUserAsync();
}
}
@@ -0,0 +1,84 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Responses.Themes;
using Lumina.Presentation.Api.Core.Endpoints.Themes.Queries.GetThemeSettings;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
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.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Themes.Queries.GetThemeSettings;
/// <summary>
/// Contains integration tests for the <see cref="GetThemeSettingsEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetThemeSettingsEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private HttpClient _client;
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
/// <summary>
/// Initializes a new instance of the <see cref="GetThemeSettingsEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetThemeSettingsEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Fact]
public async Task GetThemeSettings_WhenCalled_ShouldReturnTheThemeEngineSettings()
{
// Act
HttpResponseMessage response = await _client.GetAsync("/api/v1/themes/settings");
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
ThemeSettingsResponse? settings = await response.Content.ReadFromJsonAsync<ThemeSettingsResponse>(_jsonOptions);
Assert.NotNull(settings);
Assert.Equal(8 * 1024 * 1024, settings!.MaxArchiveBytes);
Assert.Equal("lumina-default", settings.DefaultThemeId);
}
[Fact]
public async Task GetThemeSettings_WhenCalledWithoutAuthentication_ShouldReturnTheThemeEngineSettings()
{
// Arrange
HttpClient anonymousClient = _apiFactory.CreateClient();
// Act
HttpResponseMessage response = await anonymousClient.GetAsync("/api/v1/themes/settings");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
await _apiFactory.RemoveTestUserAsync();
}
}
@@ -0,0 +1,131 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Responses.Themes;
using Lumina.Presentation.Api.Core.Endpoints.Themes.Queries.GetThemeTemplate;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.AspNetCore.Http;
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.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Themes.Queries.GetThemeTemplate;
/// <summary>
/// Contains integration tests for the <see cref="GetThemeTemplateEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetThemeTemplateEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
/// <summary>
/// Initializes a new instance of the <see cref="GetThemeTemplateEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetThemeTemplateEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
}
/// <summary>
/// Performs no setup; the template endpoint is accessed anonymously.
/// </summary>
/// <returns>A task representing the asynchronous operation.</returns>
public Task InitializeAsync()
{
return Task.CompletedTask;
}
[Fact]
public async Task GetThemeTemplate_WhenCalledWithExistingThemeAndPageKey_ShouldReturnTemplate()
{
// Arrange
await ThemeTestHelpers.WaitForBundledThemeAsync(_apiFactory);
HttpClient anonymousClient = _apiFactory.CreateClient();
// Act
HttpResponseMessage response = await anonymousClient.GetAsync("/api/v1/themes/editorial-paper/templates/shared/layout");
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
ThemeTemplateResponse? result = await response.Content.ReadFromJsonAsync<ThemeTemplateResponse>(_jsonOptions);
Assert.NotNull(result);
Assert.Equal("editorial-paper", result!.Theme.ThemeId);
Assert.False(string.IsNullOrWhiteSpace(result.Template));
}
[Fact]
public async Task GetThemeTemplate_WhenThemeDoesNotExist_ShouldReturnNotFound()
{
// Arrange
HttpClient anonymousClient = _apiFactory.CreateClient();
string themeId = "nonexistent-theme";
// Act
HttpResponseMessage response = await anonymousClient.GetAsync($"/api/v1/themes/{themeId}/templates/shared/layout");
// 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}/templates/shared/layout", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
}
[Fact]
public async Task GetThemeTemplate_WhenPageKeyIsEmpty_ShouldReturnValidationProblem()
{
// Arrange
await ThemeTestHelpers.WaitForBundledThemeAsync(_apiFactory);
HttpClient anonymousClient = _apiFactory.CreateClient();
// Act
HttpResponseMessage response = await anonymousClient.GetAsync("/api/v1/themes/editorial-paper/templates/");
// Assert
Assert.Equal(HttpStatusCode.UnprocessableContent, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors.Keys);
Assert.Contains("PageKeyCannotBeEmpty", errors["General.Validation"]);
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
await _apiFactory.RemoveTestUserAsync();
}
}
@@ -0,0 +1,95 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Responses.Themes;
using Lumina.Domain.SharedKernel.Common.Enums.Themes;
using Lumina.Presentation.Api.Core.Endpoints.Themes.Queries.GetThemes;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Themes.Queries.GetThemes;
/// <summary>
/// Contains integration tests for the <see cref="GetThemesEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetThemesEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private HttpClient _client;
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
/// <summary>
/// Initializes a new instance of the <see cref="GetThemesEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetThemesEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Fact]
public async Task GetThemes_WhenCalled_ShouldReturnTheInstalledThemes()
{
// Arrange
await ThemeTestHelpers.WaitForBundledThemeAsync(_apiFactory);
// Act
HttpResponseMessage response = await _client.GetAsync("/api/v1/themes");
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
List<ThemeResponse>? themes = await response.Content.ReadFromJsonAsync<List<ThemeResponse>>(_jsonOptions);
Assert.NotNull(themes);
ThemeResponse? bundledTheme = themes!.FirstOrDefault(theme => theme.ThemeId == "editorial-paper");
Assert.NotNull(bundledTheme);
Assert.NotEmpty(bundledTheme!.Name);
Assert.Equal(ThemeInstallSource.Bundled, bundledTheme.InstallSource);
Assert.True(bundledTheme.IsCurrent);
}
[Fact]
public async Task GetThemes_WhenCalledWithoutAuthentication_ShouldReturnUnauthorizedResult()
{
// Arrange
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
// Act
HttpResponseMessage response = await unauthenticatedClient.GetAsync("/api/v1/themes");
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
await _apiFactory.RemoveTestUserAsync();
}
}