mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 11:11:10 +00:00
Adds the unit tests for the theming feature
This commit is contained in:
1 parent
9c83e5dfa7
commit
baa6450406
47 files changed
+8234
-8
No files matched your search
+195
@@ -0,0 +1,195 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.Authorization;
|
||||
using Lumina.Presentation.Web.Common.DTO.Themes;
|
||||
using Lumina.Presentation.Web.Common.Enums.Authorization;
|
||||
using Lumina.Presentation.Web.Common.Primitives;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Common.Services;
|
||||
using Lumina.Presentation.Web.Core.Themes;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Abstractions;
|
||||
using Microsoft.AspNetCore.Mvc.ModelBinding;
|
||||
using Microsoft.AspNetCore.Mvc.Rendering;
|
||||
using Microsoft.AspNetCore.Mvc.ViewEngines;
|
||||
using Microsoft.AspNetCore.Mvc.ViewFeatures;
|
||||
using Microsoft.Extensions.Localization;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Themes;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ThemeLayoutRenderer"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ThemeLayoutRendererTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly ICompositeViewEngine _mockViewEngine;
|
||||
private readonly ITempDataProvider _mockTempDataProvider;
|
||||
private readonly IServiceProvider _mockServiceProvider;
|
||||
private readonly IHttpContextAccessor _mockHttpContextAccessor;
|
||||
private readonly IUrlService _mockUrlService;
|
||||
private readonly IStringLocalizerFactory _mockStringLocalizerFactory;
|
||||
private readonly IStringLocalizer _mockStringLocalizer;
|
||||
private readonly IAuthorizationService _mockAuthorizationService;
|
||||
private readonly IView _mockHeadView;
|
||||
private readonly IView _mockAudioPlayerView;
|
||||
private readonly IView _mockScriptsView;
|
||||
private readonly IView _mockNavMenuView;
|
||||
private readonly ThemeLayoutRenderer _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ThemeLayoutRendererTests"/> class.
|
||||
/// </summary>
|
||||
public ThemeLayoutRendererTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_mockViewEngine = Substitute.For<ICompositeViewEngine>();
|
||||
_mockTempDataProvider = Substitute.For<ITempDataProvider>();
|
||||
_mockTempDataProvider.LoadTempData(Arg.Any<HttpContext>()).Returns(new Dictionary<string, object>());
|
||||
_mockServiceProvider = Substitute.For<IServiceProvider>();
|
||||
_mockServiceProvider.GetService(typeof(IModelMetadataProvider)).Returns(new EmptyModelMetadataProvider());
|
||||
_mockHttpContextAccessor = Substitute.For<IHttpContextAccessor>();
|
||||
|
||||
_mockUrlService = Substitute.For<IUrlService>();
|
||||
_mockUrlService.GetAbsoluteUrl(Arg.Any<string>(), Arg.Any<object?>()).Returns("http://localhost/en-us");
|
||||
_mockStringLocalizer = CreateLocalizer();
|
||||
_mockStringLocalizerFactory = Substitute.For<IStringLocalizerFactory>();
|
||||
_mockStringLocalizerFactory.Create(Arg.Any<string>(), Arg.Any<string>()).Returns(_mockStringLocalizer);
|
||||
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
|
||||
_mockAuthorizationService.IsInRoleAsync("Admin", Arg.Any<CancellationToken>()).Returns(false);
|
||||
_mockAuthorizationService.HasPermissionAsync(Arg.Any<AuthorizationPermission>(), Arg.Any<CancellationToken>()).Returns(false);
|
||||
|
||||
_mockHeadView = CreateView("<head-fragment>");
|
||||
_mockAudioPlayerView = CreateView("<audio-fragment>");
|
||||
_mockScriptsView = CreateView("<scripts-fragment>");
|
||||
_mockNavMenuView = CreateView("<nav-menu-fragment>");
|
||||
_mockViewEngine.FindView(Arg.Any<ActionContext>(), "_ThemeLayoutHead", false).Returns(ViewEngineResult.Found("_ThemeLayoutHead", _mockHeadView));
|
||||
_mockViewEngine.FindView(Arg.Any<ActionContext>(), "_AudioPlayer", false).Returns(ViewEngineResult.Found("_AudioPlayer", _mockAudioPlayerView));
|
||||
_mockViewEngine.FindView(Arg.Any<ActionContext>(), "_ThemeLayoutScripts", false).Returns(ViewEngineResult.Found("_ThemeLayoutScripts", _mockScriptsView));
|
||||
_mockViewEngine.FindView(Arg.Any<ActionContext>(), "_NavMenu", false).Returns(ViewEngineResult.Found("_NavMenu", _mockNavMenuView));
|
||||
|
||||
RazorViewToStringRenderer viewRenderer = new(_mockViewEngine, _mockTempDataProvider, _mockServiceProvider, _mockHttpContextAccessor);
|
||||
ThemeNavBuilder navBuilder = new(_mockUrlService, _mockStringLocalizerFactory, _mockAuthorizationService, _mockHttpContextAccessor);
|
||||
ThemeService themeService = new(_mockApiHttpClient);
|
||||
_sut = new ThemeLayoutRenderer(themeService, new ThemeTemplateEngine(), viewRenderer, navBuilder, _mockHttpContextAccessor);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RenderAsync_WhenUserIsAuthenticated_ShouldRenderLayoutWithAllPlaceholders()
|
||||
{
|
||||
// Arrange
|
||||
_mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(user: TestHttpContextFactory.CreateAuthenticatedUser()));
|
||||
ThemeResponseDto theme = new ThemeResponseDtoFixture().Create(themeId: "editorial");
|
||||
SetupRenderDocuments(theme, layoutTemplate: "{{title}}|{{assetBase}}|{{{appHead}}}|{{{nav}}}|{{{content}}}|{{{audioPlayer}}}|{{{appScripts}}}|{{{scripts}}}|{{mainStyle}}", navTemplate: "nav:{{siteName}}");
|
||||
ThemeLayoutPageDto page = new("My Page", "<main>", "<page-script>");
|
||||
|
||||
// Act
|
||||
Result<string> result = await _sut.RenderAsync(page, "editorial", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal("My Page|/theme-assets/editorial/assets|<head-fragment>|nav:Lumina|<main>|<audio-fragment>|<scripts-fragment>|<page-script>|", result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RenderAsync_WhenUserIsAnonymous_ShouldRenderEmptyAudioPlayerAndBottomMainStyle()
|
||||
{
|
||||
// Arrange
|
||||
_mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(user: null));
|
||||
ThemeResponseDto theme = new ThemeResponseDtoFixture().Create(themeId: "editorial");
|
||||
SetupRenderDocuments(theme, layoutTemplate: "{{title}}|{{assetBase}}|{{{appHead}}}|{{{nav}}}|{{{content}}}|{{{audioPlayer}}}|{{{appScripts}}}|{{{scripts}}}|{{mainStyle}}", navTemplate: "nav:{{siteName}}");
|
||||
ThemeLayoutPageDto page = new("My Page", "<main>", "<page-script>");
|
||||
|
||||
// Act
|
||||
Result<string> result = await _sut.RenderAsync(page, "editorial", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal("My Page|/theme-assets/editorial/assets|<head-fragment>|nav:Lumina|<main>||<scripts-fragment>|<page-script>|bottom: 0px;", result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RenderAsync_WhenNavTemplateCannotBeRendered_ShouldFallBackToApplicationNavMenu()
|
||||
{
|
||||
// Arrange
|
||||
_mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(user: null));
|
||||
ThemeResponseDto theme = new ThemeResponseDtoFixture().Create(themeId: "editorial");
|
||||
SetupRenderDocuments(theme, layoutTemplate: "{{title}}|{{{nav}}}", navTemplate: "{{#unclosed}}");
|
||||
ThemeLayoutPageDto page = new("My Page", "<main>", 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()
|
||||
{
|
||||
// Arrange
|
||||
_mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(user: null));
|
||||
ThemeResponseDto theme = new ThemeResponseDtoFixture().Create(themeId: "editorial");
|
||||
SetupRenderDocuments(theme, layoutTemplate: "{{title}}", navTemplate: "nav:{{siteName}}");
|
||||
ThemeLayoutPageDto page = new("My Page", "<main>", string.Empty);
|
||||
string layoutEndpoint = ApiRoutes.Themes.GET_THEME_TEMPLATE
|
||||
.Replace("{themeId}", "editorial")
|
||||
.Replace("{*pageKey}", "shared/layout");
|
||||
string navEndpoint = ApiRoutes.Themes.GET_THEME_TEMPLATE
|
||||
.Replace("{themeId}", "editorial")
|
||||
.Replace("{*pageKey}", "shared/nav-menu");
|
||||
|
||||
// Act
|
||||
await _sut.RenderAsync(page, "editorial", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<ThemeTemplateResponseDto>(layoutEndpoint, Arg.Any<CancellationToken>());
|
||||
await _mockApiHttpClient.Received(1).GetAsync<ThemeTemplateResponseDto>(navEndpoint, Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
private void SetupRenderDocuments(ThemeResponseDto theme, string layoutTemplate, string navTemplate)
|
||||
{
|
||||
string layoutEndpoint = ApiRoutes.Themes.GET_THEME_TEMPLATE
|
||||
.Replace("{themeId}", theme.ThemeId)
|
||||
.Replace("{*pageKey}", "shared/layout");
|
||||
string navEndpoint = ApiRoutes.Themes.GET_THEME_TEMPLATE
|
||||
.Replace("{themeId}", theme.ThemeId)
|
||||
.Replace("{*pageKey}", "shared/nav-menu");
|
||||
_mockApiHttpClient.GetAsync<ThemeTemplateResponseDto>(layoutEndpoint, Arg.Any<CancellationToken>())
|
||||
.Returns(new ThemeTemplateResponseDto(theme, layoutTemplate));
|
||||
_mockApiHttpClient.GetAsync<ThemeTemplateResponseDto>(navEndpoint, Arg.Any<CancellationToken>())
|
||||
.Returns(new ThemeTemplateResponseDto(theme, navTemplate));
|
||||
}
|
||||
|
||||
private static IView CreateView(string markup)
|
||||
{
|
||||
IView view = Substitute.For<IView>();
|
||||
view.RenderAsync(Arg.Any<ViewContext>())
|
||||
.Returns(callInfo =>
|
||||
{
|
||||
callInfo.Arg<ViewContext>().Writer.Write(markup);
|
||||
return Task.CompletedTask;
|
||||
});
|
||||
return view;
|
||||
}
|
||||
|
||||
private static IStringLocalizer CreateLocalizer()
|
||||
{
|
||||
IStringLocalizer localizer = Substitute.For<IStringLocalizer>();
|
||||
localizer[Arg.Any<string>()].Returns(callInfo => new LocalizedString(callInfo.Arg<string>(), $"Localized-{callInfo.Arg<string>()}"));
|
||||
return localizer;
|
||||
}
|
||||
}
|
||||
+251
@@ -0,0 +1,251 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Authorization;
|
||||
using Lumina.Presentation.Web.Common.DTO.Themes;
|
||||
using Lumina.Presentation.Web.Common.Enums.Authorization;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Common.Services;
|
||||
using Lumina.Presentation.Web.Core.Themes;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Localization;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Security.Claims;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Themes;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ThemeNavBuilder"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ThemeNavBuilderTests
|
||||
{
|
||||
private readonly IUrlService _mockUrlService;
|
||||
private readonly IStringLocalizerFactory _mockStringLocalizerFactory;
|
||||
private readonly IStringLocalizer _mockStringLocalizer;
|
||||
private readonly IAuthorizationService _mockAuthorizationService;
|
||||
private readonly IHttpContextAccessor _mockHttpContextAccessor;
|
||||
private readonly ThemeNavBuilder _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ThemeNavBuilderTests"/> class.
|
||||
/// </summary>
|
||||
public ThemeNavBuilderTests()
|
||||
{
|
||||
_mockUrlService = Substitute.For<IUrlService>();
|
||||
_mockStringLocalizer = Substitute.For<IStringLocalizer>();
|
||||
_mockStringLocalizer[Arg.Any<string>()].Returns(callInfo => new LocalizedString(callInfo.Arg<string>(), $"Localized-{callInfo.Arg<string>()}"));
|
||||
_mockStringLocalizerFactory = Substitute.For<IStringLocalizerFactory>();
|
||||
_mockStringLocalizerFactory.Create(Arg.Any<string>(), Arg.Any<string>()).Returns(_mockStringLocalizer);
|
||||
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
|
||||
_mockHttpContextAccessor = Substitute.For<IHttpContextAccessor>();
|
||||
_sut = new ThemeNavBuilder(_mockUrlService, _mockStringLocalizerFactory, _mockAuthorizationService, _mockHttpContextAccessor);
|
||||
|
||||
StubSiteUrls();
|
||||
_mockAuthorizationService.IsInRoleAsync("Admin", Arg.Any<CancellationToken>()).Returns(false);
|
||||
_mockAuthorizationService.HasPermissionAsync(Arg.Any<AuthorizationPermission>(), Arg.Any<CancellationToken>()).Returns(false);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task BuildAsync_WhenUserIsAnonymous_ShouldNotIncludeAdministratorLibraryOrToolsSections()
|
||||
{
|
||||
// Arrange
|
||||
_mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(user: null));
|
||||
|
||||
// Act
|
||||
ThemeNavMenuDto result = await _sut.BuildAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Null(FindSection(result, "Localized-Administrator"));
|
||||
Assert.Null(FindSection(result, "Localized-Library"));
|
||||
Assert.Null(FindSection(result, "Localized-Tools"));
|
||||
Assert.NotNull(FindSection(result, "Localized-Language"));
|
||||
Assert.NotNull(FindSection(result, "Localized-Help"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task BuildAsync_WhenUserIsAnonymous_ShouldIncludeLoginEntryInsteadOfLogoutEntry()
|
||||
{
|
||||
// Arrange
|
||||
_mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(user: null));
|
||||
|
||||
// Act
|
||||
ThemeNavMenuDto result = await _sut.BuildAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
ThemeNavSectionDto accountSection = FindSection(result, "Localized-Account")!;
|
||||
Assert.Contains(accountSection.Items, entry => entry.Label == "Localized-Login");
|
||||
Assert.DoesNotContain(accountSection.Items, entry => entry.Label == "Localized-Logout");
|
||||
Assert.Equal("http://localhost/en-us/auth/login", accountSection.Items.First(entry => entry.Label == "Localized-Login").Url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task BuildAsync_WhenUserIsAuthenticated_ShouldIncludeAccountLinksAndLibrarySection()
|
||||
{
|
||||
// Arrange
|
||||
_mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(user: TestHttpContextFactory.CreateAuthenticatedUser()));
|
||||
|
||||
// Act
|
||||
ThemeNavMenuDto result = await _sut.BuildAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
ThemeNavSectionDto accountSection = FindSection(result, "Localized-Account")!;
|
||||
Assert.Contains(accountSection.Items, entry => entry.Label == "Localized-Logout");
|
||||
Assert.Contains(accountSection.Items, entry => entry.Label == "Localized-Register");
|
||||
Assert.Contains(accountSection.Items, entry => entry.Label == "Localized-ChangePassword");
|
||||
Assert.Contains(accountSection.Items, entry => entry.Label == "Localized-Profile");
|
||||
Assert.DoesNotContain(accountSection.Items, entry => entry.Label == "Localized-Login");
|
||||
|
||||
ThemeNavSectionDto librarySection = FindSection(result, "Localized-Library")!;
|
||||
Assert.Contains(librarySection.Items, entry => entry.Label == "Localized-ManageLibraries");
|
||||
Assert.DoesNotContain(librarySection.Items, entry => entry.Label == "Localized-AddNewLibrary");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task BuildAsync_WhenUserIsAdmin_ShouldIncludeAdministratorSection()
|
||||
{
|
||||
// Arrange
|
||||
_mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(user: TestHttpContextFactory.CreateAuthenticatedUser()));
|
||||
_mockAuthorizationService.IsInRoleAsync("Admin", Arg.Any<CancellationToken>()).Returns(true);
|
||||
|
||||
// Act
|
||||
ThemeNavMenuDto result = await _sut.BuildAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
ThemeNavSectionDto administratorSection = FindSection(result, "Localized-Administrator")!;
|
||||
Assert.Contains(administratorSection.Items, entry => entry.Label == "Localized-ManageRoles" && entry.Url == "http://localhost/en-us/admin/manage-roles");
|
||||
Assert.Contains(administratorSection.Items, entry => entry.Label == "Localized-ManagePermissions" && entry.Url == "http://localhost/en-us/admin/manage-permissions");
|
||||
Assert.Contains(administratorSection.Items, entry => entry.Label == "Localized-Plugins" && entry.Url == "http://localhost/en-us/admin/manage-plugins");
|
||||
Assert.Contains(administratorSection.Items, entry => entry.Label == "Localized-Themes" && entry.Url == "http://localhost/en-us/admin/manage-themes");
|
||||
await _mockAuthorizationService.Received(1).IsInRoleAsync("Admin", Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task BuildAsync_WhenUserCanCreateLibraries_ShouldIncludeAddNewLibraryEntry()
|
||||
{
|
||||
// Arrange
|
||||
_mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(user: TestHttpContextFactory.CreateAuthenticatedUser()));
|
||||
_mockAuthorizationService.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, Arg.Any<CancellationToken>()).Returns(true);
|
||||
|
||||
// Act
|
||||
ThemeNavMenuDto result = await _sut.BuildAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
ThemeNavSectionDto librarySection = FindSection(result, "Localized-Library")!;
|
||||
Assert.Contains(librarySection.Items, entry => entry.Label == "Localized-AddNewLibrary" && entry.Url == "http://localhost/en-us/libraries/manage/item");
|
||||
await _mockAuthorizationService.Received(1).HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task BuildAsync_WhenUserCannotCreateLibraries_ShouldNotIncludeAddNewLibraryEntry()
|
||||
{
|
||||
// Arrange
|
||||
_mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(user: TestHttpContextFactory.CreateAuthenticatedUser()));
|
||||
|
||||
// Act
|
||||
ThemeNavMenuDto result = await _sut.BuildAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
ThemeNavSectionDto librarySection = FindSection(result, "Localized-Library")!;
|
||||
Assert.DoesNotContain(librarySection.Items, entry => entry.Label == "Localized-AddNewLibrary");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task BuildAsync_WhenRequestHasPathAndQuery_ShouldKeepEscapedReturnUrlInLanguageEntries()
|
||||
{
|
||||
// Arrange
|
||||
DefaultHttpContext httpContext = TestHttpContextFactory.Create(user: null);
|
||||
httpContext.Request.Path = "/en-us";
|
||||
httpContext.Request.QueryString = new QueryString("?page=1");
|
||||
_mockHttpContextAccessor.HttpContext.Returns(httpContext);
|
||||
|
||||
// Act
|
||||
ThemeNavMenuDto result = await _sut.BuildAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
ThemeNavSectionDto languageSection = FindSection(result, "Localized-Language")!;
|
||||
Assert.Equal(9, languageSection.Items.Count);
|
||||
Assert.All(languageSection.Items, entry =>
|
||||
{
|
||||
Assert.Equal("lang-set", entry.CssClass);
|
||||
Assert.Contains("returnUrl=%2Fen-us%3Fpage%3D1", entry.Url);
|
||||
});
|
||||
Assert.Contains(languageSection.Items, entry => entry.Label == "English" && entry.Url!.StartsWith("http://localhost/en-us/tools/language/set-language?newCulture=en-us", StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task BuildAsync_WhenAuthenticated_ShouldIncludeSettingsEntryInDesktopToolsSection()
|
||||
{
|
||||
// Arrange
|
||||
_mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(user: TestHttpContextFactory.CreateAuthenticatedUser()));
|
||||
|
||||
// Act
|
||||
ThemeNavMenuDto result = await _sut.BuildAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
ThemeNavSectionDto toolsSection = FindSection(result, "Localized-Tools", isMobile: false)!;
|
||||
Assert.Contains(toolsSection.Items, entry => entry.Label == "Localized-Settings" && entry.Url == "http://localhost/en-us/tools/settings");
|
||||
// the desktop tools section hosts the language submenu while the mobile menu has a dedicated language section
|
||||
Assert.Contains(toolsSection.Items, entry => entry.Label == "Localized-Language" && entry.Children.Count == 9);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task BuildAsync_WhenCalled_ShouldCreateLocalizerForTheNavigationResources()
|
||||
{
|
||||
// Arrange
|
||||
_mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(user: null));
|
||||
|
||||
// Act
|
||||
await _sut.BuildAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
_mockStringLocalizerFactory.Received(1).Create("Lumina.Presentation.Web.Views.Shared._NavMenu", "Lumina.Presentation.Web");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task BuildAsync_WhenAdminCreatesLibraries_ShouldAddAddNewLibraryEntryOnce()
|
||||
{
|
||||
// Arrange
|
||||
_mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(user: TestHttpContextFactory.CreateAuthenticatedUser()));
|
||||
_mockAuthorizationService.IsInRoleAsync("Admin", Arg.Any<CancellationToken>()).Returns(true);
|
||||
_mockAuthorizationService.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, Arg.Any<CancellationToken>()).Returns(true);
|
||||
|
||||
// Act
|
||||
ThemeNavMenuDto result = await _sut.BuildAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
ThemeNavSectionDto librarySection = FindSection(result, "Localized-Library")!;
|
||||
Assert.Single(librarySection.Items, entry => entry.Label == "Localized-AddNewLibrary");
|
||||
}
|
||||
|
||||
private void StubSiteUrls()
|
||||
{
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Home.INDEX_CULTURED).Returns("http://localhost/en-us");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Authentication.LOGIN_VIEW).Returns("http://localhost/en-us/auth/login");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Authentication.RECOVER_PASSWORD_VIEW).Returns("http://localhost/en-us/auth/recover-password");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Authentication.LOGOUT).Returns("http://localhost/en-us/auth/logout");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Authentication.REGISTER_VIEW).Returns("http://localhost/en-us/auth/register");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Authentication.CHANGE_PASSWORD_VIEW).Returns("http://localhost/en-us/auth/change-password");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Authentication.PROFILE_VIEW).Returns("http://localhost/en-us/auth/profile");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Admin.MANAGE_ROLES).Returns("http://localhost/en-us/admin/manage-roles");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Admin.MANAGE_PERMISSIONS).Returns("http://localhost/en-us/admin/manage-permissions");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Plugins.INDEX).Returns("http://localhost/en-us/admin/manage-plugins");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Admin.MANAGE_THEMES).Returns("http://localhost/en-us/admin/manage-themes");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.INDEX).Returns("http://localhost/en-us/libraries/manage");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.ADD_LIBRARY).Returns("http://localhost/en-us/libraries/manage/item");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Settings.INDEX).Returns("http://localhost/en-us/tools/settings");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Language.SET_LANGUAGE).Returns("http://localhost/en-us/tools/language/set-language");
|
||||
}
|
||||
|
||||
private static ThemeNavSectionDto? FindSection(ThemeNavMenuDto menu, string label, bool isMobile = true)
|
||||
{
|
||||
IReadOnlyList<ThemeNavSectionDto> sections = isMobile ? menu.MobileSections : menu.MenubarSections;
|
||||
return sections.FirstOrDefault(section => section.Label == label);
|
||||
}
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Themes;
|
||||
using Microsoft.Extensions.Localization;
|
||||
using NSubstitute;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Themes;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ThemePageDataFactory"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ThemePageDataFactoryTests
|
||||
{
|
||||
private readonly IStringLocalizer _mockStringLocalizer;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ThemePageDataFactoryTests"/> class.
|
||||
/// </summary>
|
||||
public ThemePageDataFactoryTests()
|
||||
{
|
||||
_mockStringLocalizer = Substitute.For<IStringLocalizer>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreateLocalizedStrings_WhenLocalizerProvidesStrings_ShouldReturnDictionaryKeyedByName()
|
||||
{
|
||||
// Arrange
|
||||
LocalizedString[] localizedStrings =
|
||||
[
|
||||
new("Title", "The Title"),
|
||||
new("Search", "Search")
|
||||
];
|
||||
_mockStringLocalizer.GetAllStrings(Arg.Any<bool>()).Returns(localizedStrings);
|
||||
|
||||
// Act
|
||||
Dictionary<string, object?> result = ThemePageDataFactory.CreateLocalizedStrings(_mockStringLocalizer);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(2, result.Count);
|
||||
Assert.Equal("The Title", result["Title"]);
|
||||
Assert.Equal("Search", result["Search"]);
|
||||
_mockStringLocalizer.Received(1).GetAllStrings(includeParentCultures: true);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreateLocalizedStrings_WhenLocalizerProvidesNoStrings_ShouldReturnEmptyDictionary()
|
||||
{
|
||||
// Arrange
|
||||
_mockStringLocalizer.GetAllStrings(Arg.Any<bool>()).Returns([]);
|
||||
|
||||
// Act
|
||||
Dictionary<string, object?> result = ThemePageDataFactory.CreateLocalizedStrings(_mockStringLocalizer);
|
||||
|
||||
// Assert
|
||||
Assert.Empty(result);
|
||||
}
|
||||
}
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.Themes;
|
||||
using Lumina.Presentation.Web.Common.Primitives;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Themes;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Themes;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ThemePageRenderer"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ThemePageRendererTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly ThemePageRenderer _sut;
|
||||
private readonly ThemeResponseDtoFixture _themeResponseDtoFixture = new();
|
||||
private readonly ThemePageDtoFixture _themePageDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ThemePageRendererTests"/> class.
|
||||
/// </summary>
|
||||
public ThemePageRendererTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
ThemeService themeService = new(_mockApiHttpClient);
|
||||
_sut = new ThemePageRenderer(themeService, new ThemeTemplateEngine());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RenderAsync_WhenThemeIdProvided_ShouldRenderPageAndPopulateThemeMetadata()
|
||||
{
|
||||
// Arrange
|
||||
ThemeResponseDto theme = _themeResponseDtoFixture.Create(themeId: "editorial-paper");
|
||||
string pageKey = "home/index";
|
||||
string template = "<h1>{{title}}</h1>{{#scripts}}<script>init();</script>{{/scripts}}";
|
||||
string expectedEndpoint = ApiRoutes.Themes.GET_THEME_TEMPLATE
|
||||
.Replace("{themeId}", "editorial-paper")
|
||||
.Replace("{*pageKey}", pageKey);
|
||||
_mockApiHttpClient.GetAsync<ThemeTemplateResponseDto>(expectedEndpoint, Arg.Any<CancellationToken>())
|
||||
.Returns(new ThemeTemplateResponseDto(theme, template));
|
||||
ThemePageDto model = _themePageDtoFixture.Create(pageKey: pageKey, title: "Home");
|
||||
|
||||
// Act
|
||||
Result<ThemePageRenderResultDto> result = await _sut.RenderAsync(model, "editorial-paper", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal("<h1>Home</h1>", result.Value.Content);
|
||||
Assert.Equal("<script>init();</script>", result.Value.Script);
|
||||
Assert.Equal("editorial-paper", model.ThemeId);
|
||||
Assert.Equal("/theme-assets/editorial-paper/assets", model.AssetBase);
|
||||
Assert.StartsWith("script_", model.ScriptId);
|
||||
await _mockApiHttpClient.DidNotReceive().GetAsync<ThemeResponseDto>(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RenderAsync_WhenThemeIdMissing_ShouldResolveCurrentThemeBeforeRendering()
|
||||
{
|
||||
// Arrange
|
||||
ThemeResponseDto currentTheme = _themeResponseDtoFixture.Create(themeId: "lumina-default");
|
||||
string pageKey = "home/index";
|
||||
string expectedEndpoint = ApiRoutes.Themes.GET_THEME_TEMPLATE
|
||||
.Replace("{themeId}", "lumina-default")
|
||||
.Replace("{*pageKey}", pageKey);
|
||||
_mockApiHttpClient.GetAsync<ThemeResponseDto>(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any<CancellationToken>())
|
||||
.Returns(currentTheme);
|
||||
_mockApiHttpClient.GetAsync<ThemeTemplateResponseDto>(expectedEndpoint, Arg.Any<CancellationToken>())
|
||||
.Returns(new ThemeTemplateResponseDto(currentTheme, "{{title}}"));
|
||||
ThemePageDto model = _themePageDtoFixture.Create(pageKey: pageKey, title: "Home");
|
||||
|
||||
// Act
|
||||
Result<ThemePageRenderResultDto> result = await _sut.RenderAsync(model, null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal("lumina-default", model.ThemeId);
|
||||
Assert.Equal("Home", result.Value.Content);
|
||||
await _mockApiHttpClient.Received(1).GetAsync<ThemeResponseDto>(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RenderAsync_WhenTemplateRenderingFails_ShouldReturnFailure()
|
||||
{
|
||||
// Arrange
|
||||
ThemeResponseDto theme = _themeResponseDtoFixture.Create(themeId: "editorial-paper");
|
||||
string pageKey = "home/index";
|
||||
string expectedEndpoint = ApiRoutes.Themes.GET_THEME_TEMPLATE
|
||||
.Replace("{themeId}", "editorial-paper")
|
||||
.Replace("{*pageKey}", pageKey);
|
||||
_mockApiHttpClient.GetAsync<ThemeTemplateResponseDto>(expectedEndpoint, Arg.Any<CancellationToken>())
|
||||
.Returns(new ThemeTemplateResponseDto(theme, "{{#unclosed}}"));
|
||||
ThemePageDto model = _themePageDtoFixture.Create(pageKey: pageKey, title: "Home");
|
||||
|
||||
// Act
|
||||
Result<ThemePageRenderResultDto> result = await _sut.RenderAsync(model, "editorial-paper", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal("Theme.Template.Invalid", result.FirstError.Code);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.FileSystemManagement;
|
||||
using Lumina.Presentation.Web.Common.DTO.Themes;
|
||||
using Lumina.Presentation.Web.Common.Enums.Themes;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Themes;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Themes;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ThemeService"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ThemeServiceTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly ThemeService _sut;
|
||||
private readonly ThemeResponseDtoFixture _themeResponseDtoFixture = new();
|
||||
private readonly ThemeSettingsResponseDtoFixture _themeSettingsResponseDtoFixture = new();
|
||||
private readonly ThemeTemplateResponseDtoFixture _themeTemplateResponseDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ThemeServiceTests"/> class.
|
||||
/// </summary>
|
||||
public ThemeServiceTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = new ThemeService(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetThemesAsync_WhenApiReturnsThemes_ShouldReturnMappedThemeInfoList()
|
||||
{
|
||||
// Arrange
|
||||
ThemeResponseDto[] themes =
|
||||
[
|
||||
_themeResponseDtoFixture.Create(themeId: "editorial-paper", name: "Editorial Paper", previewPath: "preview.png", includePreviewPath: true, installSource: ThemeInstallSource.Bundled),
|
||||
_themeResponseDtoFixture.Create(themeId: "lumina-default", name: "Lumina Default", previewPath: "preview.png", includePreviewPath: true, installSource: ThemeInstallSource.Uploaded)
|
||||
];
|
||||
_mockApiHttpClient.GetAsync<ThemeResponseDto[]>(ApiRoutes.Themes.GET_THEMES, Arg.Any<CancellationToken>())
|
||||
.Returns(themes);
|
||||
|
||||
// Act
|
||||
IReadOnlyList<ThemeInfoDto> result = await _sut.GetThemesAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(2, result.Count);
|
||||
Assert.Equal("editorial-paper", result[0].Id);
|
||||
Assert.Equal("Editorial Paper", result[0].Name);
|
||||
Assert.Equal(themes[0].Description, result[0].Description);
|
||||
Assert.Equal(themes[0].Author, result[0].Author);
|
||||
Assert.Equal(themes[0].Version, result[0].Version);
|
||||
Assert.Equal("/theme-assets/editorial-paper/preview.png", result[0].PreviewUrl);
|
||||
Assert.True(result[0].IsBundled);
|
||||
Assert.False(result[1].IsBundled);
|
||||
await _mockApiHttpClient.Received(1).GetAsync<ThemeResponseDto[]>(ApiRoutes.Themes.GET_THEMES, Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetThemesAsync_WhenThemeHasNoPreviewPath_ShouldReturnPlaceholderPreviewUrl()
|
||||
{
|
||||
// Arrange
|
||||
ThemeResponseDto theme = _themeResponseDtoFixture.Create(themeId: "editorial-paper", previewPath: null);
|
||||
_mockApiHttpClient.GetAsync<ThemeResponseDto[]>(ApiRoutes.Themes.GET_THEMES, Arg.Any<CancellationToken>())
|
||||
.Returns([theme]);
|
||||
|
||||
// Act
|
||||
IReadOnlyList<ThemeInfoDto> result = await _sut.GetThemesAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("/admin/theme-placeholder.svg", result[0].PreviewUrl);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetCurrentThemeAsync_WhenApiReturnsCurrentTheme_ShouldReturnMappedThemeInfo()
|
||||
{
|
||||
// Arrange
|
||||
ThemeResponseDto theme = _themeResponseDtoFixture.Create(themeId: "editorial-paper", previewPath: "preview.png", includePreviewPath: true);
|
||||
_mockApiHttpClient.GetAsync<ThemeResponseDto>(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any<CancellationToken>())
|
||||
.Returns(theme);
|
||||
|
||||
// Act
|
||||
ThemeInfoDto result = await _sut.GetCurrentThemeAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("editorial-paper", result.Id);
|
||||
Assert.Equal(theme.Name, result.Name);
|
||||
Assert.Equal("/theme-assets/editorial-paper/preview.png", result.PreviewUrl);
|
||||
await _mockApiHttpClient.Received(1).GetAsync<ThemeResponseDto>(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetThemeSettingsAsync_WhenApiReturnsSettings_ShouldReturnSettings()
|
||||
{
|
||||
// Arrange
|
||||
ThemeSettingsResponseDto settings = _themeSettingsResponseDtoFixture.Create(maxArchiveBytes: 10 * 1024 * 1024, allowThemeScripts: true);
|
||||
_mockApiHttpClient.GetAsync<ThemeSettingsResponseDto>(ApiRoutes.Themes.GET_THEME_SETTINGS, Arg.Any<CancellationToken>())
|
||||
.Returns(settings);
|
||||
|
||||
// Act
|
||||
ThemeSettingsResponseDto result = await _sut.GetThemeSettingsAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(settings, result);
|
||||
await _mockApiHttpClient.Received(1).GetAsync<ThemeSettingsResponseDto>(ApiRoutes.Themes.GET_THEME_SETTINGS, Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetCurrentThemeAsync_WhenCalled_ShouldSendThemeIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
string themeId = "editorial-paper";
|
||||
_mockApiHttpClient.PutAsync<ThemeResponseDto, object>(Arg.Any<string>(), Arg.Any<object>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_themeResponseDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.SetCurrentThemeAsync(themeId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutAsync<ThemeResponseDto, object>(
|
||||
ApiRoutes.Themes.SET_CURRENT_THEME,
|
||||
Arg.Is<object>(payload => payload.GetType().GetProperty("ThemeId")!.GetValue(payload)!.ToString()! == themeId),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InstallAsync_WhenCalled_ShouldUploadArchiveToInstallEndpoint()
|
||||
{
|
||||
// Arrange
|
||||
ThemeResponseDto installedTheme = _themeResponseDtoFixture.Create(themeId: "installed-theme");
|
||||
using (MemoryStream archiveStream = new([1, 2, 3, 4]))
|
||||
{
|
||||
string fileName = "theme-pack.zip";
|
||||
_mockApiHttpClient.PostMultipartAsync<ThemeResponseDto>(Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(installedTheme);
|
||||
|
||||
// Act
|
||||
ThemeInfoDto result = await _sut.InstallAsync(archiveStream, fileName, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("installed-theme", result.Id);
|
||||
await _mockApiHttpClient.Received(1).PostMultipartAsync<ThemeResponseDto>(
|
||||
ApiRoutes.Themes.INSTALL_THEME,
|
||||
archiveStream,
|
||||
fileName,
|
||||
"archive",
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteThemeAsync_WhenCalled_ShouldDeleteThemeWithResolvedEndpoint()
|
||||
{
|
||||
// Arrange
|
||||
string themeId = "editorial-paper";
|
||||
string expectedEndpoint = ApiRoutes.Themes.DELETE_THEME.Replace("{themeId}", themeId);
|
||||
|
||||
// Act
|
||||
await _sut.DeleteThemeAsync(themeId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(expectedEndpoint, Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRenderDocumentAsync_WhenThemeIdProvided_ShouldFetchTemplateWithResolvedRoute()
|
||||
{
|
||||
// Arrange
|
||||
string themeId = "editorial-paper";
|
||||
string pageKey = "shared/layout";
|
||||
ThemeTemplateResponseDto templateResponse = _themeTemplateResponseDtoFixture.Create(theme: _themeResponseDtoFixture.Create(themeId: themeId), template: "Hello {{title}}");
|
||||
string expectedEndpoint = ApiRoutes.Themes.GET_THEME_TEMPLATE
|
||||
.Replace("{themeId}", themeId)
|
||||
.Replace("{*pageKey}", pageKey);
|
||||
_mockApiHttpClient.GetAsync<ThemeTemplateResponseDto>(expectedEndpoint, Arg.Any<CancellationToken>())
|
||||
.Returns(templateResponse);
|
||||
|
||||
// Act
|
||||
ThemeRenderDocumentDto result = await _sut.GetRenderDocumentAsync(pageKey, themeId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(themeId, result.Theme.Id);
|
||||
Assert.Equal("Hello {{title}}", result.Template);
|
||||
await _mockApiHttpClient.DidNotReceive().GetAsync<ThemeResponseDto>(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any<CancellationToken>());
|
||||
await _mockApiHttpClient.Received(1).GetAsync<ThemeTemplateResponseDto>(expectedEndpoint, Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRenderDocumentAsync_WhenThemeIdMissing_ShouldResolveCurrentThemeFirst()
|
||||
{
|
||||
// Arrange
|
||||
string pageKey = "home/index";
|
||||
ThemeResponseDto currentTheme = _themeResponseDtoFixture.Create(themeId: "lumina-default");
|
||||
ThemeTemplateResponseDto templateResponse = _themeTemplateResponseDtoFixture.Create(theme: _themeResponseDtoFixture.Create(themeId: "lumina-default"), template: "Home");
|
||||
string expectedEndpoint = ApiRoutes.Themes.GET_THEME_TEMPLATE
|
||||
.Replace("{themeId}", "lumina-default")
|
||||
.Replace("{*pageKey}", pageKey);
|
||||
_mockApiHttpClient.GetAsync<ThemeResponseDto>(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any<CancellationToken>())
|
||||
.Returns(currentTheme);
|
||||
_mockApiHttpClient.GetAsync<ThemeTemplateResponseDto>(expectedEndpoint, Arg.Any<CancellationToken>())
|
||||
.Returns(templateResponse);
|
||||
|
||||
// Act
|
||||
ThemeRenderDocumentDto result = await _sut.GetRenderDocumentAsync(pageKey, null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("lumina-default", result.Theme.Id);
|
||||
await _mockApiHttpClient.Received(1).GetAsync<ThemeResponseDto>(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any<CancellationToken>());
|
||||
await _mockApiHttpClient.Received(1).GetAsync<ThemeTemplateResponseDto>(expectedEndpoint, Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task BuildArchiveAsync_WhenApiReturnsBlob_ShouldReturnZipArchiveWithResolvedFileName()
|
||||
{
|
||||
// Arrange
|
||||
string themeId = "editorial-paper";
|
||||
byte[] data = [0x50, 0x4B, 0x03, 0x04];
|
||||
_mockApiHttpClient.GetBlobAsync(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new BlobDataDto { Data = data, ContentType = "application/zip" });
|
||||
string expectedEndpoint = ApiRoutes.Themes.GET_THEME_ARCHIVE.Replace("{themeId}", themeId);
|
||||
|
||||
// Act
|
||||
ThemeArchiveDto result = await _sut.BuildArchiveAsync(themeId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal($"{themeId}.zip", result.FileName);
|
||||
using (MemoryStream content = new())
|
||||
{
|
||||
await result.Content.CopyToAsync(content);
|
||||
Assert.Equal(data, content.ToArray());
|
||||
}
|
||||
|
||||
await _mockApiHttpClient.Received(1).GetBlobAsync(expectedEndpoint, Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+478
@@ -0,0 +1,478 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Themes;
|
||||
using Lumina.Presentation.Web.Common.Primitives;
|
||||
using Lumina.Presentation.Web.Core.Themes;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Models;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Themes;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ThemeTemplateEngine"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ThemeTemplateEngineTests
|
||||
{
|
||||
private readonly ThemeTemplateEngine _sut;
|
||||
private readonly SectionModelFixture _sectionModelFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ThemeTemplateEngineTests"/> class.
|
||||
/// </summary>
|
||||
public ThemeTemplateEngineTests()
|
||||
{
|
||||
_sut = new ThemeTemplateEngine();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RenderPage_WhenVariableValueContainsHtml_ShouldEscapeOutput()
|
||||
{
|
||||
// Arrange
|
||||
Dictionary<string, object?> model = new() { ["value"] = "<b>&\"quote\"" };
|
||||
string template = "{{value}}";
|
||||
|
||||
// Act
|
||||
Result<ThemePageRenderResultDto> result = _sut.RenderPage(template, model);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal("<b>&"quote"", result.Value.Content);
|
||||
Assert.Equal(string.Empty, result.Value.Script);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RenderPage_WhenRawVariableTagUsed_ShouldNotEscapeOutput()
|
||||
{
|
||||
// Arrange
|
||||
Dictionary<string, object?> model = new() { ["value"] = "<b>raw</b>" };
|
||||
|
||||
// Act
|
||||
Result<ThemePageRenderResultDto> ampersandResult = _sut.RenderPage("{{&value}}", model);
|
||||
Result<ThemePageRenderResultDto> tripleResult = _sut.RenderPage("{{{value}}}", model);
|
||||
|
||||
// Assert
|
||||
Assert.True(ampersandResult.IsSuccess);
|
||||
Assert.Equal("<b>raw</b>", ampersandResult.Value.Content);
|
||||
Assert.True(tripleResult.IsSuccess);
|
||||
Assert.Equal("<b>raw</b>", tripleResult.Value.Content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RenderPage_WhenVariableMissing_ShouldRenderEmptyString()
|
||||
{
|
||||
// Arrange
|
||||
Dictionary<string, object?> model = new() { ["title"] = "Present" };
|
||||
|
||||
// Act
|
||||
Result<ThemePageRenderResultDto> result = _sut.RenderPage("{{title}}|{{missing}}", model);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal("Present|", result.Value.Content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RenderPage_WhenVariableIsBoolean_ShouldRenderLowercaseLiteral()
|
||||
{
|
||||
// Arrange
|
||||
Dictionary<string, object?> model = new() { ["enabled"] = true, ["disabled"] = false };
|
||||
|
||||
// Act
|
||||
Result<ThemePageRenderResultDto> result = _sut.RenderPage("{{enabled}}/{{disabled}}", model);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal("true/false", result.Value.Content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RenderPage_WhenDottedExpressionUsed_ShouldResolveNestedProperty()
|
||||
{
|
||||
// Arrange
|
||||
Dictionary<string, object?> model = new()
|
||||
{
|
||||
["user"] = new Dictionary<string, object?> { ["name"] = "Ada" }
|
||||
};
|
||||
|
||||
// Act
|
||||
Result<ThemePageRenderResultDto> result = _sut.RenderPage("Hello {{user.name}}", model);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal("Hello Ada", result.Value.Content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RenderPage_WhenCollectionCountRequested_ShouldRenderCollectionCount()
|
||||
{
|
||||
// Arrange
|
||||
Dictionary<string, object?> model = new() { ["items"] = new List<object> { "a", "b", "c" } };
|
||||
|
||||
// Act
|
||||
Result<ThemePageRenderResultDto> result = _sut.RenderPage("{{items.Count}}", model);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal("3", result.Value.Content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RenderPage_WhenSectionIsTruthy_ShouldRenderChildren()
|
||||
{
|
||||
// Arrange
|
||||
Dictionary<string, object?> model = new() { ["section"] = true, ["text"] = "inside" };
|
||||
|
||||
// Act
|
||||
Result<ThemePageRenderResultDto> result = _sut.RenderPage("{{#section}}{{text}}{{/section}}", model);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal("inside", result.Value.Content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RenderPage_WhenSectionIsObject_ShouldRenderChildrenWithObjectScope()
|
||||
{
|
||||
// Arrange
|
||||
Dictionary<string, object?> model = new()
|
||||
{
|
||||
["section"] = _sectionModelFixture.Create(text: "scoped")
|
||||
};
|
||||
|
||||
// Act
|
||||
Result<ThemePageRenderResultDto> result = _sut.RenderPage("{{#section}}{{text}}{{/section}}", model);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal("scoped", result.Value.Content);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // unresolved section
|
||||
[InlineData(false)] // boolean false
|
||||
[InlineData("")] // empty string
|
||||
public void RenderPage_WhenSectionIsFalsy_ShouldSkipChildren(object? sectionValue)
|
||||
{
|
||||
// Arrange
|
||||
Dictionary<string, object?> model = new() { ["section"] = sectionValue, ["text"] = "hidden" };
|
||||
|
||||
// Act
|
||||
Result<ThemePageRenderResultDto> result = _sut.RenderPage("before{{#section}}{{text}}{{/section}}after", model);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal("beforeafter", result.Value.Content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RenderPage_WhenSectionIsEmptyCollection_ShouldSkipChildren()
|
||||
{
|
||||
// Arrange
|
||||
Dictionary<string, object?> model = new() { ["section"] = new List<object>() };
|
||||
|
||||
// Act
|
||||
Result<ThemePageRenderResultDto> result = _sut.RenderPage("a{{#section}}x{{/section}}b", model);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal("ab", result.Value.Content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RenderPage_WhenSectionIsCollection_ShouldRenderChildrenPerItem()
|
||||
{
|
||||
// Arrange
|
||||
Dictionary<string, object?> model = new()
|
||||
{
|
||||
["items"] = new List<object>
|
||||
{
|
||||
new Dictionary<string, object?> { ["name"] = "A" },
|
||||
new Dictionary<string, object?> { ["name"] = "B" }
|
||||
}
|
||||
};
|
||||
|
||||
// Act
|
||||
Result<ThemePageRenderResultDto> result = _sut.RenderPage("{{#items}}[{{name}}]{{/items}}", model);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal("[A][B]", result.Value.Content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RenderPage_WhenSectionIteratesScalarItems_ShouldRenderCurrentScopeValue()
|
||||
{
|
||||
// Arrange
|
||||
Dictionary<string, object?> model = new() { ["items"] = new List<object> { "one", "two" } };
|
||||
|
||||
// Act
|
||||
Result<ThemePageRenderResultDto> result = _sut.RenderPage("{{#items}}{{.}};{{/items}}", model);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal("one;two;", result.Value.Content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RenderPage_WhenParentTraversalUsed_ShouldResolveFromParentScope()
|
||||
{
|
||||
// Arrange
|
||||
Dictionary<string, object?> model = new()
|
||||
{
|
||||
["title"] = "Parent",
|
||||
["items"] = new List<object>
|
||||
{
|
||||
new Dictionary<string, object?> { ["name"] = "A" },
|
||||
new Dictionary<string, object?> { ["name"] = "B" }
|
||||
}
|
||||
};
|
||||
|
||||
// Act
|
||||
Result<ThemePageRenderResultDto> result = _sut.RenderPage("{{#items}}{{../title}}/{{name}};{{/items}}", model);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal("Parent/A;Parent/B;", result.Value.Content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RenderPage_WhenInvertedSectionIsFalsy_ShouldRenderChildren()
|
||||
{
|
||||
// Arrange
|
||||
Dictionary<string, object?> model = new() { ["section"] = null };
|
||||
|
||||
// Act
|
||||
Result<ThemePageRenderResultDto> result = _sut.RenderPage("{{^section}}fallback{{/section}}", model);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal("fallback", result.Value.Content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RenderPage_WhenInvertedSectionIsTruthy_ShouldSkipChildren()
|
||||
{
|
||||
// Arrange
|
||||
Dictionary<string, object?> model = new() { ["section"] = "present" };
|
||||
|
||||
// Act
|
||||
Result<ThemePageRenderResultDto> result = _sut.RenderPage("a{{^section}}fallback{{/section}}b", model);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal("ab", result.Value.Content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RenderPage_WhenTopLevelScriptsSectionPresent_ShouldSeparateScriptFromContent()
|
||||
{
|
||||
// Arrange
|
||||
Dictionary<string, object?> model = new() { ["title"] = "Page", ["script"] = "console.log('x');" };
|
||||
|
||||
// Act
|
||||
Result<ThemePageRenderResultDto> result = _sut.RenderPage(
|
||||
"<h1>{{title}}</h1>{{#scripts}}<script>{{{script}}}</script>{{/scripts}}",
|
||||
model);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal("<h1>Page</h1>", result.Value.Content);
|
||||
Assert.Equal("<script>console.log('x');</script>", result.Value.Script);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RenderPage_WhenScriptsSectionIsNamedDifferentlyInCase_ShouldStillSplitIt()
|
||||
{
|
||||
// Arrange
|
||||
Dictionary<string, object?> model = new() { ["title"] = "Page" };
|
||||
|
||||
// Act
|
||||
Result<ThemePageRenderResultDto> result = _sut.RenderPage(
|
||||
"content{{#SCRIPTS}}script{{/SCRIPTS}}",
|
||||
model);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal("content", result.Value.Content);
|
||||
Assert.Equal("script", result.Value.Script);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RenderPage_WhenScriptsSectionIsNestedInsideAnotherSection_ShouldKeepItInContent()
|
||||
{
|
||||
// Arrange
|
||||
Dictionary<string, object?> model = new()
|
||||
{
|
||||
["items"] = new List<object>
|
||||
{
|
||||
new Dictionary<string, object?> { ["name"] = "A", ["scripts"] = true, ["script"] = "x" }
|
||||
}
|
||||
};
|
||||
|
||||
// Act
|
||||
Result<ThemePageRenderResultDto> result = _sut.RenderPage(
|
||||
"{{#items}}{{name}}{{#scripts}}{{script}}{{/scripts}}{{/items}}",
|
||||
model);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal("Ax", result.Value.Content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RenderPage_WhenTemplateContainsOnlyComments_ShouldReturnEmptyContent()
|
||||
{
|
||||
// Arrange
|
||||
Dictionary<string, object?> model = new() { ["title"] = "Page" };
|
||||
|
||||
// Act
|
||||
Result<ThemePageRenderResultDto> result = _sut.RenderPage("{{! this is a comment }}", model);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal(string.Empty, result.Value.Content);
|
||||
Assert.Equal(string.Empty, result.Value.Script);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RenderPage_WhenSectionIsNotClosed_ShouldReturnTemplateError()
|
||||
{
|
||||
// Arrange
|
||||
Dictionary<string, object?> model = new() { ["section"] = true };
|
||||
|
||||
// Act
|
||||
Result<ThemePageRenderResultDto> result = _sut.RenderPage("{{#section}}content", model);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal("Theme.Template.Invalid", result.FirstError.Code);
|
||||
Assert.Contains("not closed", result.FirstError.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RenderPage_WhenClosingTagHasNoOpeningSection_ShouldReturnTemplateError()
|
||||
{
|
||||
// Act
|
||||
Result<ThemePageRenderResultDto> result = _sut.RenderPage("{{/section}}", new Dictionary<string, object?>());
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal("Theme.Template.Invalid", result.FirstError.Code);
|
||||
Assert.Contains("no matching opening section", result.FirstError.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RenderPage_WhenClosingTagMismatchesOpeningSection_ShouldReturnTemplateError()
|
||||
{
|
||||
// Act
|
||||
Result<ThemePageRenderResultDto> result = _sut.RenderPage("{{#first}}x{{/second}}", new Dictionary<string, object?>());
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal("Theme.Template.Invalid", result.FirstError.Code);
|
||||
Assert.Contains("closed by", result.FirstError.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RenderPage_WhenEmptyTagUsed_ShouldReturnTemplateError()
|
||||
{
|
||||
// Act
|
||||
Result<ThemePageRenderResultDto> result = _sut.RenderPage("before{{}}after", new Dictionary<string, object?>());
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal("Theme.Template.Invalid", result.FirstError.Code);
|
||||
Assert.Contains("Empty template tags", result.FirstError.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RenderPage_WhenTagIsNotClosed_ShouldReturnTemplateError()
|
||||
{
|
||||
// Act
|
||||
Result<ThemePageRenderResultDto> result = _sut.RenderPage("before{{value", new Dictionary<string, object?>());
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal("Theme.Template.Invalid", result.FirstError.Code);
|
||||
Assert.Contains("not closed", result.FirstError.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RenderPage_WhenRawTagIsNotClosed_ShouldReturnTemplateError()
|
||||
{
|
||||
// Act
|
||||
Result<ThemePageRenderResultDto> result = _sut.RenderPage("before{{{value", new Dictionary<string, object?>());
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal("Theme.Template.Invalid", result.FirstError.Code);
|
||||
Assert.Contains("not closed", result.FirstError.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RenderPage_WhenExpressionIsTooLong_ShouldReturnTemplateError()
|
||||
{
|
||||
// Arrange
|
||||
string expression = new('a', 121);
|
||||
string template = $"{{{{{expression}}}}}";
|
||||
|
||||
// Act
|
||||
Result<ThemePageRenderResultDto> result = _sut.RenderPage(template, new Dictionary<string, object?>());
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal("Theme.Template.Invalid", result.FirstError.Code);
|
||||
Assert.Contains("too long", result.FirstError.Description);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("{{bad-name}}")] // hyphen is not a valid name part character
|
||||
[InlineData("{{two words}}")] // whitespace inside the expression
|
||||
[InlineData("{{a..b}}")] // empty name part
|
||||
public void RenderPage_WhenExpressionIsInvalid_ShouldReturnTemplateError(string template)
|
||||
{
|
||||
// Act
|
||||
Result<ThemePageRenderResultDto> result = _sut.RenderPage(template, new Dictionary<string, object?>());
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal("Theme.Template.Invalid", result.FirstError.Code);
|
||||
Assert.Contains("is invalid", result.FirstError.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RenderPage_WhenSectionsAreNestedDeeperThanTheLimit_ShouldReturnTemplateError()
|
||||
{
|
||||
// Arrange
|
||||
string template = string.Concat(Enumerable.Repeat("{{#section}}", 33))
|
||||
+ string.Concat(Enumerable.Repeat("{{/section}}", 33));
|
||||
|
||||
// Act
|
||||
Result<ThemePageRenderResultDto> result = _sut.RenderPage(template, new Dictionary<string, object?>());
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal("Theme.Template.Invalid", result.FirstError.Code);
|
||||
Assert.Contains("nested more than", result.FirstError.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RenderPage_WhenRenderedOutputExceedsTheSafetyLimit_ShouldReturnTemplateError()
|
||||
{
|
||||
// Arrange
|
||||
int limit = 4 * 1024 * 1024;
|
||||
Dictionary<string, object?> model = new() { ["text"] = new string('a', limit + 1) };
|
||||
|
||||
// Act
|
||||
Result<ThemePageRenderResultDto> result = _sut.RenderPage("{{text}}", model);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal("Theme.Template.Invalid", result.FirstError.Code);
|
||||
Assert.Contains("safety limit", result.FirstError.Description);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user