From 02f27655f8c1c50208fa23939e9dd8ff35bc5eae Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Fri, 21 Aug 2026 09:43:19 -0700 Subject: [PATCH] Adds the integration tests for the theming feature --- .../Common/Setup/ThemeTestHelpers.cs | 42 +++ .../DeleteTheme/DeleteThemeEndpointTests.cs | 223 ++++++++++++++++ .../InstallTheme/InstallThemeEndpointTests.cs | 237 +++++++++++++++++ .../SetCurrentThemeEndpointTests.cs | 244 ++++++++++++++++++ .../GetCurrentThemeEndpointTests.cs | 88 +++++++ .../GetThemeArchiveEndpointTests.cs | 111 ++++++++ .../GetThemeAssetEndpointTests.cs | 130 ++++++++++ .../GetThemeSettingsEndpointTests.cs | 84 ++++++ .../GetThemeTemplateEndpointTests.cs | 131 ++++++++++ .../GetThemes/GetThemesEndpointTests.cs | 95 +++++++ 10 files changed, 1385 insertions(+) create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/ThemeTestHelpers.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Management/DeleteTheme/DeleteThemeEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Management/SetCurrentTheme/SetCurrentThemeEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Queries/GetCurrentTheme/GetCurrentThemeEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Queries/GetThemeArchive/GetThemeArchiveEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Queries/GetThemeAsset/GetThemeAssetEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Queries/GetThemeSettings/GetThemeSettingsEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Queries/GetThemes/GetThemesEndpointTests.cs diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/ThemeTestHelpers.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/ThemeTestHelpers.cs new file mode 100644 index 00000000..8dc3e89b --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/ThemeTestHelpers.cs @@ -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; + +/// +/// Helpers shared by the theme integration tests. +/// +[ExcludeFromCodeCoverage] +public static class ThemeTestHelpers +{ + /// + /// Waits until the bundled 'editorial-paper' theme has been installed and activated by the theme detection job at startup. + /// + /// The shared API factory whose database is polled. + /// A task representing the asynchronous operation. + 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(); + + 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."); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Management/DeleteTheme/DeleteThemeEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Management/DeleteTheme/DeleteThemeEndpointTests.cs new file mode 100644 index 00000000..539bf863 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Management/DeleteTheme/DeleteThemeEndpointTests.cs @@ -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; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DeleteThemeEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly TestThemeArchiveFixture _themeArchiveFixture = new(); + private readonly List _installedThemeIds = []; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public DeleteThemeEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes an authenticated admin API client. + /// + 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(); + 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? themes = await listResponse.Content.ReadFromJsonAsync>(_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? problemDetails = JsonSerializer.Deserialize>(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? problemDetails = JsonSerializer.Deserialize>(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? problemDetails = JsonSerializer.Deserialize>(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); + } + + /// + /// Installs a test theme through the API and returns its manifest id. + /// + /// The manifest id of the installed theme. + private async Task 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; + } + + /// + /// 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. + /// + public async Task DisposeAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + 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(); + 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().ExecuteDeleteAsync(); + await dbContext.Set().ExecuteDeleteAsync(); + await dbContext.Set().ExecuteDeleteAsync(); + await dbContext.Set().ExecuteDeleteAsync(); + await dbContext.Set().ExecuteDeleteAsync(); + await dbContext.Set().ExecuteDeleteAsync(); + + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpointTests.cs new file mode 100644 index 00000000..00b5214c --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpointTests.cs @@ -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; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class InstallThemeEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly TestThemeArchiveFixture _themeArchiveFixture = new(); + private readonly List _installedThemeIds = []; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public InstallThemeEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes an authenticated admin API client. + /// + 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(_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? themes = await listResponse.Content.ReadFromJsonAsync>(_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(); + 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? problemDetails = JsonSerializer.Deserialize>(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? problemDetails = JsonSerializer.Deserialize>(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? errors = problemDetails["errors"].Deserialize>(_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? problemDetails = JsonSerializer.Deserialize>(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); + } + + /// + /// Disposes API factory resources, removing the installed test themes and the authorization seed data of the admin test user. + /// + public async Task DisposeAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + 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(); + 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().ExecuteDeleteAsync(); + await dbContext.Set().ExecuteDeleteAsync(); + await dbContext.Set().ExecuteDeleteAsync(); + await dbContext.Set().ExecuteDeleteAsync(); + await dbContext.Set().ExecuteDeleteAsync(); + await dbContext.Set().ExecuteDeleteAsync(); + + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Management/SetCurrentTheme/SetCurrentThemeEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Management/SetCurrentTheme/SetCurrentThemeEndpointTests.cs new file mode 100644 index 00000000..9af4be62 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Management/SetCurrentTheme/SetCurrentThemeEndpointTests.cs @@ -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; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class SetCurrentThemeEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly TestThemeArchiveFixture _themeArchiveFixture = new(); + private readonly List _installedThemeIds = []; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public SetCurrentThemeEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes an authenticated admin API client. + /// + 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(_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(_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? problemDetails = JsonSerializer.Deserialize>(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? problemDetails = JsonSerializer.Deserialize>(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? errors = problemDetails["errors"].Deserialize>(_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? problemDetails = JsonSerializer.Deserialize>(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); + } + + /// + /// Installs a test theme through the API and returns its manifest id. + /// + /// Optional manifest id of the theme to install. + /// The manifest id of the installed theme. + private async Task 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; + } + + /// + /// 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. + /// + public async Task DisposeAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + 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(); + 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().ExecuteDeleteAsync(); + await dbContext.Set().ExecuteDeleteAsync(); + await dbContext.Set().ExecuteDeleteAsync(); + await dbContext.Set().ExecuteDeleteAsync(); + await dbContext.Set().ExecuteDeleteAsync(); + await dbContext.Set().ExecuteDeleteAsync(); + + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Queries/GetCurrentTheme/GetCurrentThemeEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Queries/GetCurrentTheme/GetCurrentThemeEndpointTests.cs new file mode 100644 index 00000000..d4c9900c --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Queries/GetCurrentTheme/GetCurrentThemeEndpointTests.cs @@ -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; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetCurrentThemeEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetCurrentThemeEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + 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(_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); + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Queries/GetThemeArchive/GetThemeArchiveEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Queries/GetThemeArchive/GetThemeArchiveEndpointTests.cs new file mode 100644 index 00000000..c03e0f3c --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Queries/GetThemeArchive/GetThemeArchiveEndpointTests.cs @@ -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; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetThemeArchiveEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetThemeArchiveEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + 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? problemDetails = JsonSerializer.Deserialize>(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); + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Queries/GetThemeAsset/GetThemeAssetEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Queries/GetThemeAsset/GetThemeAssetEndpointTests.cs new file mode 100644 index 00000000..2a6d278b --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Queries/GetThemeAsset/GetThemeAssetEndpointTests.cs @@ -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; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetThemeAssetEndpointTests : IClassFixture, IAsyncLifetime +{ + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetThemeAssetEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + } + + /// + /// Performs no setup; the asset endpoint is accessed anonymously. + /// + /// A task representing the asynchronous operation. + 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? problemDetails = JsonSerializer.Deserialize>(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? problemDetails = JsonSerializer.Deserialize>(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? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("General.Validation", errors.Keys); + Assert.Contains("ThemeAssetPathCannotBeEmpty", errors["General.Validation"]); + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Queries/GetThemeSettings/GetThemeSettingsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Queries/GetThemeSettings/GetThemeSettingsEndpointTests.cs new file mode 100644 index 00000000..5062e6f2 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Queries/GetThemeSettings/GetThemeSettingsEndpointTests.cs @@ -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; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetThemeSettingsEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetThemeSettingsEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + 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(_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); + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpointTests.cs new file mode 100644 index 00000000..5e235fc8 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpointTests.cs @@ -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; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetThemeTemplateEndpointTests : IClassFixture, IAsyncLifetime +{ + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetThemeTemplateEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + } + + /// + /// Performs no setup; the template endpoint is accessed anonymously. + /// + /// A task representing the asynchronous operation. + 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(_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? problemDetails = JsonSerializer.Deserialize>(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? problemDetails = JsonSerializer.Deserialize>(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? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("General.Validation", errors.Keys); + Assert.Contains("PageKeyCannotBeEmpty", errors["General.Validation"]); + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Queries/GetThemes/GetThemesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Queries/GetThemes/GetThemesEndpointTests.cs new file mode 100644 index 00000000..69a1b9f5 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Queries/GetThemes/GetThemesEndpointTests.cs @@ -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; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetThemesEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetThemesEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + 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? themes = await response.Content.ReadFromJsonAsync>(_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); + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + await _apiFactory.RemoveTestUserAsync(); + } +}