Falls back to the unstyled application views when a theme template is missing

This commit is contained in:
BinaryAlley committed 2026-08-29 13:11:16 +03:00
1 parent f4b90a5aea
commit 3192b9c585
11 files changed
+366 -301

No files matched your search

@@ -11,10 +11,12 @@ using Lumina.Contracts.Responses.Themes;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Themes;
using Microsoft.Extensions.Logging;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -31,6 +33,7 @@ public class GetThemeTemplateQueryHandlerTests
private readonly IThemeService _mockThemeService;
private readonly IValidator<GetThemeTemplateQuery> _mockValidator;
private readonly IThemeRepository _mockThemeRepository;
private readonly ILogger<GetThemeTemplateQueryHandler> _mockLogger;
private readonly GetThemeTemplateQueryHandler _sut;
private readonly GetThemeTemplateQueryFixture _getThemeTemplateQueryFixture = new();
private readonly ThemeEntityFixture _themeEntityFixture = new();
@@ -44,12 +47,13 @@ public class GetThemeTemplateQueryHandlerTests
_mockThemeService = Substitute.For<IThemeService>();
_mockValidator = Substitute.For<IValidator<GetThemeTemplateQuery>>();
_mockThemeRepository = Substitute.For<IThemeRepository>();
_mockLogger = Substitute.For<ILogger<GetThemeTemplateQueryHandler>>();
_mockValidator.Validate(Arg.Any<GetThemeTemplateQuery>())
.Returns([]);
_mockUnitOfWork.ThemeRepository.Returns(_mockThemeRepository);
_sut = new GetThemeTemplateQueryHandler(_mockUnitOfWork, _mockThemeService, _mockValidator);
_sut = new GetThemeTemplateQueryHandler(_mockUnitOfWork, _mockThemeService, _mockValidator, _mockLogger);
}
[Fact]
@@ -166,6 +170,51 @@ public class GetThemeTemplateQueryHandlerTests
await _mockThemeService.DidNotReceive().RestoreBundledThemeAsync(Arg.Any<string>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenTemplateIsNotFoundForBundledTheme_ShouldNotRestoreBundledTheme()
{
// Arrange
GetThemeTemplateQuery query = _getThemeTemplateQueryFixture.Create();
ThemeEntity theme = _themeEntityFixture.Create(themeId: query.ThemeId, installSource: ThemeInstallSource.Bundled, isDeleted: false);
_mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(theme));
_mockThemeService.GetTemplateAsync(theme.ThemeId, query.PageKey!, Arg.Any<CancellationToken>())
.Returns(Errors.Themes.ThemeTemplateNotFound);
// Act
Result<ThemeTemplateResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Themes.ThemeTemplateNotFound, result.FirstError);
await _mockThemeService.DidNotReceive().RestoreBundledThemeAsync(Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockThemeService.Received(1).GetTemplateAsync(theme.ThemeId, query.PageKey!, Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenRestoreThrowsForBundledTheme_ShouldReturnTemplateErrorInsteadOfThrowing()
{
// Arrange
GetThemeTemplateQuery query = _getThemeTemplateQueryFixture.Create();
ThemeEntity theme = _themeEntityFixture.Create(themeId: query.ThemeId, installSource: ThemeInstallSource.Bundled, isDeleted: false);
Error templateError = Errors.Themes.ThemeFilesUnreadable;
_mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(theme));
_mockThemeService.GetTemplateAsync(theme.ThemeId, query.PageKey!, Arg.Any<CancellationToken>())
.Returns(templateError);
_mockThemeService.RestoreBundledThemeAsync(theme.ThemeId, Arg.Any<CancellationToken>())
.Returns(Task.FromException<Result<Success>>(new IOException("The theme storage is locked.")));
// Act
Result<ThemeTemplateResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(templateError, result.FirstError);
await _mockThemeService.Received(1).RestoreBundledThemeAsync(theme.ThemeId, Arg.Any<CancellationToken>());
await _mockThemeService.Received(1).GetTemplateAsync(theme.ThemeId, query.PageKey!, Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenTemplateLoadFailsAndRestoreFails_ShouldReturnTemplateError()
{
@@ -275,6 +275,26 @@ public class ThemeDetectionSyncJobTests : IDisposable
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task StartAsync_WhenRestoringBundledThemeThrows_ShouldNotCrashTheJob()
{
// Arrange
ThemeEntity brokenTheme = _themeEntityFixture.Create(themeId: "bundled-theme", installSource: ThemeInstallSource.Bundled, isDeleted: false);
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ThemeEntity>>([brokenTheme]));
_mockThemeService.HasThemePack("bundled-theme").Returns(false);
_mockThemeService.GetBundledThemeArchivePaths().Returns([]);
_mockThemeService.RestoreBundledThemeAsync("bundled-theme", Arg.Any<CancellationToken>())
.Returns(Task.FromException<Result<Success>>(new IOException("The theme storage is locked.")));
_mockThemeRepository.UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>()).Returns(Result.From(Result.Updated));
// Act
await StartAndWaitForExecutionAsync(CreateSut());
// Assert
await _mockThemeService.Received(1).RestoreBundledThemeAsync("bundled-theme", Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task StartAsync_WhenLastBundledThemePackCannotBeRestored_ShouldKeepAndActivateTheTheme()
{
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Models.DTO.Themes;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
@@ -200,7 +201,7 @@ public class ThemeServiceTests : IDisposable
// Act
await InstallValidThemeAsync(firstArchive);
await InstallValidThemeAsync(secondArchive);
Result<string> templateResult = await _sut.GetTemplateAsync("test-theme", "unknown-page", CancellationToken.None);
Result<string> templateResult = await _sut.GetTemplateAsync("test-theme", "default", CancellationToken.None);
// Assert
Assert.True(templateResult.IsSuccess);
@@ -210,6 +211,23 @@ public class ThemeServiceTests : IDisposable
Assert.Equal("test-theme", Path.GetFileName(themeDirectories[0]));
}
[Fact]
public async Task InstallAsync_WhenThemeDestinationIsBlocked_ShouldReturnThemeFilesUnreadableInsteadOfThrowing()
{
// Arrange
byte[] archive = _themePackFixture.Create(themeId: "test-theme");
// the destination path is blocked by an existing file, so the extracted pack cannot be moved into place
Directory.CreateDirectory(_options.StoragePath);
File.WriteAllText(Path.Combine(_options.StoragePath, "test-theme"), "blocked");
// Act
Result<ThemeManifestDto> result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal("ThemeFilesUnreadable", result.FirstError.Description);
}
[Fact]
public async Task InstallAsync_WhenArchiveExceedsMaxArchiveBytes_ShouldReturnArchiveTooLargeError()
{
@@ -558,7 +576,7 @@ public class ThemeServiceTests : IDisposable
}
[Fact]
public async Task InstallAsync_WhenManifestDeclaresNoTemplates_ShouldReturnPackageInvalidError()
public async Task InstallAsync_WhenManifestDeclaresNoTemplates_ShouldInstallSuccessfully()
{
// Arrange
byte[] archive = _themePackFixture.Create(templates: new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase));
@@ -567,7 +585,7 @@ public class ThemeServiceTests : IDisposable
Result<ThemeManifestDto> result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None);
// Assert
AssertPackageInvalid(result, "between 1 and 32");
Assert.True(result.IsSuccess);
}
[Fact]
@@ -583,7 +601,7 @@ public class ThemeServiceTests : IDisposable
Result<ThemeManifestDto> result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None);
// Assert
AssertPackageInvalid(result, "between 1 and 32");
AssertPackageInvalid(result, "at most 32");
}
[Fact]
@@ -641,7 +659,7 @@ public class ThemeServiceTests : IDisposable
}
[Fact]
public async Task InstallAsync_WhenManifestLacksDefaultTemplate_ShouldReturnPackageInvalidError()
public async Task InstallAsync_WhenManifestLacksDefaultTemplate_ShouldInstallSuccessfully()
{
// Arrange
Dictionary<string, string> templates = new(StringComparer.OrdinalIgnoreCase)
@@ -654,7 +672,7 @@ public class ThemeServiceTests : IDisposable
Result<ThemeManifestDto> result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None);
// Assert
AssertPackageInvalid(result, "default");
Assert.True(result.IsSuccess);
}
[Fact]
@@ -889,7 +907,7 @@ public class ThemeServiceTests : IDisposable
}
[Fact]
public async Task GetTemplateAsync_WhenNoTemplateResolves_ShouldFallBackToDefaultTemplate()
public async Task GetTemplateAsync_WhenNoTemplateResolves_ShouldReturnThemeTemplateNotFound()
{
// Arrange
byte[] archive = CreateThemeWithTemplates();
@@ -899,15 +917,15 @@ public class ThemeServiceTests : IDisposable
Result<string> result = await _sut.GetTemplateAsync("test-theme", "unknown-page", CancellationToken.None);
// Assert
Assert.True(result.IsSuccess);
Assert.Equal(DEFAULT_TEMPLATE, result.Value);
Assert.True(result.IsFailure);
Assert.Equal(Errors.Themes.ThemeTemplateNotFound, result.FirstError);
}
[Theory]
[InlineData("../secret")] // parent scope traversal attempt
[InlineData("/etc/passwd")] // rooted path attempt
[InlineData("templates//nested")] // empty segment attempt
public async Task GetTemplateAsync_WhenPageKeyAttemptsToEscapeTheThemePack_ShouldFallBackToDefaultTemplate(string pageKey)
public async Task GetTemplateAsync_WhenPageKeyAttemptsToEscapeTheThemePack_ShouldReturnThemeTemplateNotFound(string pageKey)
{
// Arrange
byte[] archive = CreateThemeWithTemplates();
@@ -916,9 +934,58 @@ public class ThemeServiceTests : IDisposable
// Act
Result<string> result = await _sut.GetTemplateAsync("test-theme", pageKey, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Themes.ThemeTemplateNotFound, result.FirstError);
}
[Fact]
public async Task GetTemplateAsync_WhenSharedLayoutTemplateIsMissing_ShouldReturnThemeTemplateNotFound()
{
// Arrange
byte[] archive = CreateThemeWithTemplates();
await InstallValidThemeAsync(archive);
// Act
Result<string> result = await _sut.GetTemplateAsync("test-theme", "shared/layout", CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Themes.ThemeTemplateNotFound, result.FirstError);
}
[Fact]
public async Task GetTemplateAsync_WhenSharedNavMenuTemplateIsMissing_ShouldReturnThemeTemplateNotFound()
{
// Arrange
byte[] archive = CreateThemeWithTemplates();
await InstallValidThemeAsync(archive);
// Act
Result<string> result = await _sut.GetTemplateAsync("test-theme", "shared/nav-menu", CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Themes.ThemeTemplateNotFound, result.FirstError);
}
[Fact]
public async Task GetTemplateAsync_WhenSharedNavMenuMirrorExists_ShouldReturnTheMirroredTemplate()
{
// Arrange
const string NAV_TEMPLATE = "<html><body>nav menu</body></html>";
byte[] archive = _themePackFixture.Create(additionalFiles: new Dictionary<string, string>
{
["templates/shared/nav-menu.html"] = NAV_TEMPLATE
});
await InstallValidThemeAsync(archive);
// Act
Result<string> result = await _sut.GetTemplateAsync("test-theme", "shared/nav-menu", CancellationToken.None);
// Assert
Assert.True(result.IsSuccess);
Assert.Equal(DEFAULT_TEMPLATE, result.Value);
Assert.Equal(NAV_TEMPLATE, result.Value);
}
[Fact]
@@ -953,7 +1020,7 @@ public class ThemeServiceTests : IDisposable
}
[Fact]
public async Task GetTemplateAsync_WhenMirroredTemplateFileWasRemoved_ShouldFallBackToDefaultTemplate()
public async Task GetTemplateAsync_WhenMirroredTemplateFileWasRemoved_ShouldReturnThemeTemplateNotFound()
{
// Arrange
byte[] archive = CreateThemeWithTemplates();
@@ -964,8 +1031,8 @@ public class ThemeServiceTests : IDisposable
Result<string> result = await _sut.GetTemplateAsync("test-theme", "library/book", CancellationToken.None);
// Assert
Assert.True(result.IsSuccess);
Assert.Equal(DEFAULT_TEMPLATE, result.Value);
Assert.True(result.IsFailure);
Assert.Equal(Errors.Themes.ThemeTemplateNotFound, result.FirstError);
}
[Fact]
@@ -20,6 +20,7 @@ using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -139,6 +140,29 @@ public class ThemeLayoutRendererTests
_mockViewEngine.Received(1).FindView(Arg.Any<ActionContext>(), "_NavMenu", false);
}
[Fact]
public async Task RenderAsync_WhenNavDocumentCannotBeLoaded_ShouldFallBackToApplicationNavMenu()
{
// Arrange
_mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(user: null));
ThemeResponseDto theme = _themeResponseDtoFixture.Create(themeId: "editorial");
SetupRenderDocuments(theme, layoutTemplate: "{{title}}|{{{nav}}}", navTemplate: "nav:{{siteName}}");
string navEndpoint = ApiRoutes.Themes.GET_THEME_TEMPLATE
.Replace("{themeId}", "editorial")
.Replace("{*pageKey}", "shared/nav-menu");
_mockApiHttpClient.GetAsync<ThemeTemplateResponseDto>(navEndpoint, Arg.Any<CancellationToken>())
.Returns(Task.FromException<ThemeTemplateResponseDto>(new HttpRequestException("The navigation template is unavailable.")));
ThemeLayoutPageDto page = _themeLayoutPageDtoFixture.Create(title: "My Page", content: "<main>", script: string.Empty);
// Act
Result<string> result = await _sut.RenderAsync(page, "editorial", CancellationToken.None);
// Assert
Assert.True(result.IsSuccess);
Assert.Equal("My Page|<nav-menu-fragment>", result.Value);
_mockViewEngine.Received(1).FindView(Arg.Any<ActionContext>(), "_NavMenu", false);
}
[Fact]
public async Task RenderAsync_WhenCalled_ShouldResolveLayoutAndNavDocumentsFromTheme()
{