Moves the file explorer styling and layout into the bundled themes

This commit is contained in:
BinaryAlley committed 2026-08-29 16:28:58 +03:00
1 parent 3f69693332
commit a32f80337b
72 files changed
+1577 -1682

No files matched your search

@@ -0,0 +1,52 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Presentation.Web.Common.DTO.Themes;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Themes;
/// <summary>
/// Fixture class for generating <see cref="ThemeFileSystemBrowserConfigurationDto"/> test data.
/// </summary>
[ExcludeFromCodeCoverage]
public class ThemeFileSystemBrowserConfigurationDtoFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a new <see cref="ThemeFileSystemBrowserConfigurationDto"/> instance with randomized test data.
/// </summary>
/// <param name="serverBasePath">Optional base URL of the remote API.</param>
/// <param name="clientBasePath">Optional base URL of the Web application.</param>
/// <param name="path">Optional initial path displayed by the file system browser.</param>
/// <param name="viewMode">Optional initial view mode of the file system browser.</param>
/// <param name="iconSize">Optional initial icon size of the file system browser.</param>
/// <returns>A configured <see cref="ThemeFileSystemBrowserConfigurationDto"/> instance.</returns>
public ThemeFileSystemBrowserConfigurationDto Create(
string? serverBasePath = null,
string? clientBasePath = null,
string? path = null,
string? viewMode = null,
string? iconSize = null)
{
return new ThemeFileSystemBrowserConfigurationDto(
ServerBasePath: serverBasePath ?? $"http://localhost:{_faker.Random.UShort()}/api/v1/",
ClientBasePath: clientBasePath ?? $"http://localhost:{_faker.Random.UShort()}/",
Path: path ?? (_faker.Random.Bool() ? "/" : "C:\\Users\\"),
ViewMode: viewMode ?? _faker.Random.Word(),
IconSize: iconSize ?? _faker.Random.Word());
}
/// <summary>
/// Creates multiple <see cref="ThemeFileSystemBrowserConfigurationDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="ThemeFileSystemBrowserConfigurationDto"/> instances.</returns>
public List<ThemeFileSystemBrowserConfigurationDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,62 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Presentation.Web.Common.DTO.Themes;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Themes;
/// <summary>
/// Fixture class for generating <see cref="ThemeFileSystemBrowserDto"/> test data.
/// </summary>
[ExcludeFromCodeCoverage]
public class ThemeFileSystemBrowserDtoFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a new <see cref="ThemeFileSystemBrowserDto"/> instance with randomized test data.
/// </summary>
/// <param name="appBase">Optional absolute base URL of the Web application.</param>
/// <param name="assetBase">Optional base URL of the theme assets.</param>
/// <param name="iconBaseUrl">Optional base URL of the theme file type icons.</param>
/// <param name="fileIconsUrl">Optional URL of the theme file icons mapping.</param>
/// <param name="treeNodeTemplate">Optional raw template source of the tree view node.</param>
/// <param name="explorerItemTemplate">Optional raw template source of the explorer item.</param>
/// <param name="pathSegmentTemplate">Optional raw template source of the address bar path segment.</param>
/// <param name="strings">Optional localized strings of the file system browser.</param>
/// <returns>A configured <see cref="ThemeFileSystemBrowserDto"/> instance.</returns>
public ThemeFileSystemBrowserDto Create(
string? appBase = null,
string? assetBase = null,
string? iconBaseUrl = null,
string? fileIconsUrl = null,
string? treeNodeTemplate = null,
string? explorerItemTemplate = null,
string? pathSegmentTemplate = null,
IReadOnlyDictionary<string, object?>? strings = null)
{
string themeId = _faker.Lorem.Word();
return new ThemeFileSystemBrowserDto(
AppBase: appBase ?? $"https://localhost:{_faker.Random.UShort()}/",
AssetBase: assetBase ?? $"/theme-assets/{themeId}/assets",
IconBaseUrl: iconBaseUrl ?? $"/theme-assets/{themeId}/assets/images/icons",
FileIconsUrl: fileIconsUrl ?? $"/theme-assets/{themeId}/assets/file-icons.json",
TreeNodeTemplate: treeNodeTemplate ?? "<div class=\"tree-node\" data-path=\"{{path}}\">{{name}}</div>",
ExplorerItemTemplate: explorerItemTemplate ?? "<div class=\"e {{cssClass}}\" data-path=\"{{path}}\">{{name}}</div>",
PathSegmentTemplate: pathSegmentTemplate ?? "<li id=\"{{id}}\">{{path}}</li>",
Strings: strings ?? new Dictionary<string, object?> { ["cancel"] = "Cancel" });
}
/// <summary>
/// Creates multiple <see cref="ThemeFileSystemBrowserDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="ThemeFileSystemBrowserDto"/> instances.</returns>
public List<ThemeFileSystemBrowserDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -1,7 +1,10 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.DTO.Libraries;
using Lumina.Presentation.Web.Common.DTO.Themes;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.EditLibrary;
using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries;
using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
using System;
@@ -21,6 +24,8 @@ public class EditLibraryViewEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
private readonly LibraryDtoFixture _libraryDtoFixture = new();
private readonly ThemeResponseDtoFixture _themeResponseDtoFixture = new();
private readonly ThemeTemplateResponseDtoFixture _themeTemplateResponseDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="EditLibraryViewEndpointTests"/> class.
@@ -50,4 +55,66 @@ public class EditLibraryViewEndpointTests : IClassFixture<LuminaWebFactory>
Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType);
Assert.Contains($"libraries/{libraryId}", _apiFactory.ApiClientStub.GetEndpointsCalled);
}
[Fact]
public async Task EditLibraryView_WhenThemeProvidesFileSystemBrowserTemplates_ShouldRenderThemedComponent()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid libraryId = Guid.NewGuid();
LibraryDto expectedLibrary = _libraryDtoFixture.Create(id: libraryId, title: "Books", libraryType: "Book");
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}", expectedLibrary);
ThemeResponseDto theme = _themeResponseDtoFixture.Create(themeId: "lumina-default");
_apiFactory.ApiClientStub.RegisterGetResponse(ApiRoutes.Themes.GET_CURRENT_THEME, theme);
RegisterThemeTemplate(theme, "shared/file-system-browser", "<template id=\"fsb-template-tree-node\">{{{treeNodeTemplate}}}</template><div id=\"file-system-browser-dialog\">themed</div>");
RegisterThemeTemplate(theme, "shared/file-system-browser/tree-node", "<div class=\"tree-node\">{{name}}</div>");
RegisterThemeTemplate(theme, "shared/file-system-browser/explorer-item", "<div class=\"e\">{{name}}</div>");
RegisterThemeTemplate(theme, "shared/file-system-browser/path-segment", "<li>{{path}}</li>");
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
// Act
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/libraries/manage/item/{libraryId}");
string content = await response.Content.ReadAsStringAsync();
// Assert
response.EnsureSuccessStatusCode();
Assert.Contains("id=\"fsb-template-tree-node\"", content);
Assert.Contains("initFileSystemBrowser(", content);
Assert.Contains("themed", content);
}
[Fact]
public async Task EditLibraryView_WhenThemeDoesNotProvideFileSystemBrowserTemplate_ShouldRenderApplicationFallbackComponent()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid libraryId = Guid.NewGuid();
LibraryDto expectedLibrary = _libraryDtoFixture.Create(id: libraryId, title: "Books", libraryType: "Book");
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}", expectedLibrary);
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
// Act
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/libraries/manage/item/{libraryId}");
string content = await response.Content.ReadAsStringAsync();
// Assert
response.EnsureSuccessStatusCode();
Assert.Contains("id=\"file-system-browser-dialog\"", content);
Assert.DoesNotContain("fsb-template-tree-node", content);
Assert.Contains("initFileSystemBrowser(", content);
}
/// <summary>
/// Registers the theme template response returned for the specified page key of the given theme.
/// </summary>
/// <param name="theme">The theme the template belongs to.</param>
/// <param name="pageKey">The page key of the template.</param>
/// <param name="template">The template source returned for the document.</param>
private void RegisterThemeTemplate(ThemeResponseDto theme, string pageKey, string template)
{
string endpoint = ApiRoutes.Themes.GET_THEME_TEMPLATE
.Replace("{themeId}", theme.ThemeId)
.Replace("{*pageKey}", pageKey);
_apiFactory.ApiClientStub.RegisterGetResponse(endpoint, _themeTemplateResponseDtoFixture.Create(theme: theme, template: template));
}
}
@@ -0,0 +1,123 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.DTO.Themes;
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;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.Themes;
/// <summary>
/// Contains unit tests for the <see cref="ThemeFileSystemBrowserBuilder"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ThemeFileSystemBrowserBuilderTests
{
private readonly IStringLocalizerFactory _mockStringLocalizerFactory;
private readonly IStringLocalizer _mockStringLocalizer;
private readonly IHttpContextAccessor _mockHttpContextAccessor;
private readonly ThemeFileSystemBrowserBuilder _sut;
/// <summary>
/// Initializes a new instance of the <see cref="ThemeFileSystemBrowserBuilderTests"/> class.
/// </summary>
public ThemeFileSystemBrowserBuilderTests()
{
_mockStringLocalizer = CreateLocalizer();
_mockStringLocalizerFactory = Substitute.For<IStringLocalizerFactory>();
_mockStringLocalizerFactory.Create(Arg.Any<string>(), Arg.Any<string>()).Returns(_mockStringLocalizer);
_mockHttpContextAccessor = Substitute.For<IHttpContextAccessor>();
_sut = new ThemeFileSystemBrowserBuilder(_mockStringLocalizerFactory, _mockHttpContextAccessor);
}
[Fact]
public void Build_WhenCalled_ShouldResolveThemeAssetUrlsFromAssetBase()
{
// Arrange
// Act
ThemeFileSystemBrowserDto model = _sut.Build("/theme-assets/editorial/assets", "<div>{{name}}</div>", "<div>{{name}}</div>", "<li>{{path}}</li>");
// Assert
Assert.Equal("/theme-assets/editorial/assets", model.AssetBase);
Assert.Equal("/theme-assets/editorial/assets/images/icons", model.IconBaseUrl);
Assert.Equal("/theme-assets/editorial/assets/file-icons.json", model.FileIconsUrl);
}
[Fact]
public void Build_WhenCalled_ShouldKeepTheSubTemplatesOfTheDynamicContent()
{
// Arrange
// Act
ThemeFileSystemBrowserDto model = _sut.Build("/theme-assets/editorial/assets", "<div class=\"tree-node\">{{name}}</div>", "<div class=\"e\">{{name}}</div>", "<li>{{path}}</li>");
// Assert
Assert.Equal("<div class=\"tree-node\">{{name}}</div>", model.TreeNodeTemplate);
Assert.Equal("<div class=\"e\">{{name}}</div>", model.ExplorerItemTemplate);
Assert.Equal("<li>{{path}}</li>", model.PathSegmentTemplate);
}
[Fact]
public void Build_WhenCalled_ShouldLocalizeAllFileSystemBrowserStrings()
{
// Arrange
// Act
ThemeFileSystemBrowserDto model = _sut.Build("/theme-assets/editorial/assets", string.Empty, string.Empty, string.Empty);
// Assert
string[] expectedKeys =
[
"listView", "detailsView", "smallIconsView", "mediumIconsView", "largeIconsView", "extraLargeIconsView",
"back", "forward", "upOneLevel", "toggleTreeView", "toggleThumbnails", "toggleHiddenItems",
"toggleSelectionMode", "editPath", "navigate", "newDirectory", "favoriteDirectory",
"name", "directory", "cancel", "open"
];
foreach (string key in expectedKeys)
{
Assert.True(model.Strings.TryGetValue(key, out object? value), $"The '{key}' string is missing.");
Assert.StartsWith("Localized-", Assert.IsType<string>(value));
}
}
[Fact]
public void Build_WhenRequestIsAvailable_ShouldResolveAppBaseFromCurrentRequest()
{
// Arrange
DefaultHttpContext httpContext = TestHttpContextFactory.Create();
httpContext.Request.Scheme = "https";
httpContext.Request.Host = new HostString("localhost", 5001);
_mockHttpContextAccessor.HttpContext.Returns(httpContext);
// Act
ThemeFileSystemBrowserDto model = _sut.Build("/theme-assets/editorial/assets", string.Empty, string.Empty, string.Empty);
// Assert
Assert.Equal("https://localhost:5001/", model.AppBase);
}
[Fact]
public void Build_WhenRequestIsUnavailable_ShouldReturnEmptyAppBase()
{
// Arrange
_mockHttpContextAccessor.HttpContext.Returns((HttpContext?)null);
// Act
ThemeFileSystemBrowserDto model = _sut.Build("/theme-assets/editorial/assets", string.Empty, string.Empty, string.Empty);
// Assert
Assert.Equal(string.Empty, model.AppBase);
}
/// <summary>
/// Creates a substitute string localizer that returns a string prefixed with "Localized-".
/// </summary>
/// <returns>The created substitute string localizer.</returns>
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;
}
}
@@ -0,0 +1,232 @@
#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 Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Localization;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.Themes;
/// <summary>
/// Contains unit tests for the <see cref="ThemeFileSystemBrowserRenderer"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ThemeFileSystemBrowserRendererTests
{
private readonly IApiHttpClient _mockApiHttpClient;
private readonly IHttpContextAccessor _mockHttpContextAccessor;
private readonly IStringLocalizerFactory _mockStringLocalizerFactory;
private readonly IStringLocalizer _mockStringLocalizer;
private readonly ThemeFileSystemBrowserRenderer _sut;
private readonly ThemeResponseDtoFixture _themeResponseDtoFixture = new();
private readonly ThemeTemplateResponseDtoFixture _themeTemplateResponseDtoFixture = new();
private readonly ThemeFileSystemBrowserConfigurationDtoFixture _themeFileSystemBrowserConfigurationDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ThemeFileSystemBrowserRendererTests"/> class.
/// </summary>
public ThemeFileSystemBrowserRendererTests()
{
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
_mockHttpContextAccessor = Substitute.For<IHttpContextAccessor>();
_mockStringLocalizer = CreateLocalizer();
_mockStringLocalizerFactory = Substitute.For<IStringLocalizerFactory>();
_mockStringLocalizerFactory.Create(Arg.Any<string>(), Arg.Any<string>()).Returns(_mockStringLocalizer);
ThemeService themeService = new(_mockApiHttpClient);
ThemeFileSystemBrowserBuilder builder = new(_mockStringLocalizerFactory, _mockHttpContextAccessor);
_sut = new ThemeFileSystemBrowserRenderer(themeService, new ThemeTemplateEngine(), builder);
}
[Fact]
public async Task RenderAsync_WhenShellTemplateRendered_ShouldReturnThemedContentWithSubTemplatesAndInitScript()
{
// Arrange
ThemeResponseDto theme = _themeResponseDtoFixture.Create(themeId: "editorial");
SetupRenderDocuments(theme,
shellTemplate: "<div id=\"file-system-browser-dialog\">{{assetBase}}|{{iconBaseUrl}}|{{fileIconsUrl}}|{{strings.cancel}}</div><template id=\"fsb-template-tree-node\">{{{treeNodeTemplate}}}</template>",
treeNodeTemplate: "<div class=\"tree-node\" data-path=\"{{path}}\">{{name}}</div>",
explorerItemTemplate: "<div class=\"e\">{{name}}</div>",
pathSegmentTemplate: "<li>{{path}}</li>");
ThemeFileSystemBrowserConfigurationDto configuration = _themeFileSystemBrowserConfigurationDtoFixture.Create(path: "C:\\Users\\", viewMode: "list", iconSize: "large");
// Act
Result<string> result = await _sut.RenderAsync(configuration, CancellationToken.None);
// Assert
Assert.True(result.IsSuccess);
Assert.Contains("/theme-assets/editorial/assets", result.Value);
Assert.Contains("/theme-assets/editorial/assets/images/icons", result.Value);
Assert.Contains("data-path=\"{{path}}\"", result.Value);
Assert.Contains("initFileSystemBrowser(", result.Value);
Assert.Contains("serverBasePath", result.Value);
}
[Fact]
public async Task RenderAsync_WhenSubTemplateIsMissing_ShouldRenderEmptySubTemplate()
{
// Arrange
ThemeResponseDto theme = _themeResponseDtoFixture.Create(themeId: "editorial");
SetupRenderDocuments(theme,
shellTemplate: "<template id=\"fsb-template-tree-node\">{{{treeNodeTemplate}}}</template>",
treeNodeTemplate: "not-returned",
explorerItemTemplate: "not-returned",
pathSegmentTemplate: "not-returned");
StubSubTemplateFailure(theme.ThemeId, "shared/file-system-browser/tree-node");
ThemeFileSystemBrowserConfigurationDto configuration = _themeFileSystemBrowserConfigurationDtoFixture.Create();
// Act
Result<string> result = await _sut.RenderAsync(configuration, CancellationToken.None);
// Assert
Assert.True(result.IsSuccess);
Assert.Contains("<template id=\"fsb-template-tree-node\"></template>", result.Value);
}
[Fact]
public async Task RenderAsync_WhenShellDocumentCannotBeLoaded_ShouldReturnTemplateUnavailableError()
{
// Arrange
_mockApiHttpClient.GetAsync<ThemeResponseDto>(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any<CancellationToken>())
.Returns(Task.FromException<ThemeResponseDto>(new HttpRequestException("The theme API is unavailable.")));
ThemeFileSystemBrowserConfigurationDto configuration = _themeFileSystemBrowserConfigurationDtoFixture.Create();
// Act
Result<string> result = await _sut.RenderAsync(configuration, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal("Theme.Template.Unavailable", result.FirstError.Code);
}
[Fact]
public async Task RenderAsync_WhenShellTemplateIsInvalid_ShouldReturnTemplateUnavailableError()
{
// Arrange
ThemeResponseDto theme = _themeResponseDtoFixture.Create(themeId: "editorial");
SetupRenderDocuments(theme,
shellTemplate: "{{#unclosed}}",
treeNodeTemplate: string.Empty,
explorerItemTemplate: string.Empty,
pathSegmentTemplate: string.Empty);
ThemeFileSystemBrowserConfigurationDto configuration = _themeFileSystemBrowserConfigurationDtoFixture.Create();
// Act
Result<string> result = await _sut.RenderAsync(configuration, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal("Theme.Template.Invalid", result.FirstError.Code);
}
[Fact]
public async Task RenderAsync_WhenCalled_ShouldFetchShellAndAllSubTemplatesFromActiveTheme()
{
// Arrange
ThemeResponseDto theme = _themeResponseDtoFixture.Create(themeId: "editorial");
SetupRenderDocuments(theme, "shell", "tree", "item", "segment");
ThemeFileSystemBrowserConfigurationDto configuration = _themeFileSystemBrowserConfigurationDtoFixture.Create();
// Act
await _sut.RenderAsync(configuration, CancellationToken.None);
// Assert
string[] pageKeys =
[
"shared/file-system-browser",
"shared/file-system-browser/tree-node",
"shared/file-system-browser/explorer-item",
"shared/file-system-browser/path-segment"
];
foreach (string pageKey in pageKeys)
{
string endpoint = ApiRoutes.Themes.GET_THEME_TEMPLATE
.Replace("{themeId}", "editorial")
.Replace("{*pageKey}", pageKey);
await _mockApiHttpClient.Received(1).GetAsync<ThemeTemplateResponseDto>(endpoint, Arg.Any<CancellationToken>());
}
}
[Fact]
public async Task RenderAsync_WhenCalled_ShouldEscapeInitialPathInInitializationScript()
{
// Arrange
ThemeResponseDto theme = _themeResponseDtoFixture.Create(themeId: "editorial");
SetupRenderDocuments(theme, "shell", "tree", "item", "segment");
ThemeFileSystemBrowserConfigurationDto configuration = _themeFileSystemBrowserConfigurationDtoFixture.Create(path: "C:\\Users\\", viewMode: "list", iconSize: "large");
// Act
Result<string> result = await _sut.RenderAsync(configuration, CancellationToken.None);
// Assert
Assert.True(result.IsSuccess);
Assert.Contains(@"C:\\Users\\", result.Value);
}
/// <summary>
/// Creates a substitute string localizer that returns a string prefixed with "Localized-".
/// </summary>
/// <returns>The created substitute string localizer.</returns>
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;
}
/// <summary>
/// Stubs the API responses that return the component shell and sub templates of the given theme, together with the current theme.
/// </summary>
/// <param name="theme">The theme whose templates are stubbed.</param>
/// <param name="shellTemplate">The template returned for the component shell document.</param>
/// <param name="treeNodeTemplate">The template returned for the tree node document.</param>
/// <param name="explorerItemTemplate">The template returned for the explorer item document.</param>
/// <param name="pathSegmentTemplate">The template returned for the path segment document.</param>
private void SetupRenderDocuments(ThemeResponseDto theme, string shellTemplate, string treeNodeTemplate, string explorerItemTemplate, string pathSegmentTemplate)
{
_mockApiHttpClient.GetAsync<ThemeResponseDto>(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any<CancellationToken>())
.Returns(theme);
StubTemplateResponse(theme.ThemeId, "shared/file-system-browser", shellTemplate);
StubTemplateResponse(theme.ThemeId, "shared/file-system-browser/tree-node", treeNodeTemplate);
StubTemplateResponse(theme.ThemeId, "shared/file-system-browser/explorer-item", explorerItemTemplate);
StubTemplateResponse(theme.ThemeId, "shared/file-system-browser/path-segment", pathSegmentTemplate);
}
/// <summary>
/// Stubs the API response that returns a single theme template document.
/// </summary>
/// <param name="themeId">The manifest id of the theme.</param>
/// <param name="pageKey">The page key of the template.</param>
/// <param name="template">The template returned for the document.</param>
private void StubTemplateResponse(string themeId, string pageKey, string template)
{
string endpoint = ApiRoutes.Themes.GET_THEME_TEMPLATE
.Replace("{themeId}", themeId)
.Replace("{*pageKey}", pageKey);
_mockApiHttpClient.GetAsync<ThemeTemplateResponseDto>(endpoint, Arg.Any<CancellationToken>())
.Returns(_themeTemplateResponseDtoFixture.Create(theme: _themeResponseDtoFixture.Create(themeId: themeId), template: template));
}
/// <summary>
/// Stubs the API response of a theme template document to fail, as when the theme does not provide the template.
/// </summary>
/// <param name="themeId">The manifest id of the theme.</param>
/// <param name="pageKey">The page key of the template.</param>
private void StubSubTemplateFailure(string themeId, string pageKey)
{
string endpoint = ApiRoutes.Themes.GET_THEME_TEMPLATE
.Replace("{themeId}", themeId)
.Replace("{*pageKey}", pageKey);
_mockApiHttpClient.GetAsync<ThemeTemplateResponseDto>(endpoint, Arg.Any<CancellationToken>())
.Returns(Task.FromException<ThemeTemplateResponseDto>(new HttpRequestException("The sub template is unavailable.")));
}
}
@@ -23,6 +23,7 @@ public class ThemeTemplateEngineTests
private readonly ThemeNavMenuDtoFixture _themeNavMenuDtoFixture = new();
private readonly ThemeNavSectionDtoFixture _themeNavSectionDtoFixture = new();
private readonly ThemeNavEntryDtoFixture _themeNavEntryDtoFixture = new();
private readonly ThemeFileSystemBrowserDtoFixture _themeFileSystemBrowserDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ThemeTemplateEngineTests"/> class.
@@ -158,6 +159,24 @@ public class ThemeTemplateEngineTests
Assert.Equal("Tools:[Language]English,Francais,Settings", result.Value.Content);
}
[Fact]
public void RenderPage_WhenFileSystemBrowserModelUsed_ShouldResolveStringsAndInlineRawSubTemplates()
{
// Arrange
ThemeFileSystemBrowserDto model = _themeFileSystemBrowserDtoFixture.Create(
assetBase: "/theme-assets/editorial/assets",
treeNodeTemplate: "<div class=\"tree-node\" data-path=\"{{path}}\">{{name}}</div>",
strings: new Dictionary<string, object?> { ["cancel"] = "Annuler" });
string template = "{{assetBase}}|{{strings.cancel}}|<template id=\"fsb-template-tree-node\">{{{treeNodeTemplate}}}</template>";
// Act
Result<ThemePageRenderResultDto> result = _sut.RenderPage(template, model);
// Assert
Assert.True(result.IsSuccess);
Assert.Equal("/theme-assets/editorial/assets|Annuler|<template id=\"fsb-template-tree-node\"><div class=\"tree-node\" data-path=\"{{path}}\">{{name}}</div></template>", result.Value.Content);
}
[Fact]
public void RenderPage_WhenSectionIsTruthy_ShouldRenderChildren()
{
@@ -0,0 +1,104 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.Configuration;
using Lumina.Presentation.Web.Common.DTO.Themes;
using Lumina.Presentation.Web.Common.Primitives;
using Lumina.Presentation.Web.Core.Themes;
using Lumina.Presentation.Web.Core.ViewComponents;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ViewComponents;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Options;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.ViewComponents;
/// <summary>
/// Contains unit tests for the <see cref="FileSystemBrowserViewComponent"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class FileSystemBrowserViewComponentTests
{
private readonly IOptions<ServerConfigurationDto> _serverConfigurationOptions;
private readonly ThemeFileSystemBrowserRenderer _mockRenderer;
private readonly FileSystemBrowserViewComponent _sut;
/// <summary>
/// Initializes a new instance of the <see cref="FileSystemBrowserViewComponentTests"/> class.
/// </summary>
public FileSystemBrowserViewComponentTests()
{
_serverConfigurationOptions = Options.Create(new ServerConfigurationDto
{
ApiVersion = '1',
BaseAddress = "http://localhost",
Port = 5214
});
ThemeService themeService = new(Substitute.For<IApiHttpClient>());
ThemeFileSystemBrowserBuilder builder = new(Substitute.For<IStringLocalizerFactory>(), Substitute.For<IHttpContextAccessor>());
_mockRenderer = Substitute.For<ThemeFileSystemBrowserRenderer>(themeService, new ThemeTemplateEngine(), builder);
_sut = new FileSystemBrowserViewComponent(_serverConfigurationOptions, _mockRenderer);
}
[Fact]
public async Task InvokeAsync_WhenThemedRenderSucceeds_ShouldReturnContentWithRenderedHtml()
{
// Arrange
_mockRenderer.RenderAsync(Arg.Any<ThemeFileSystemBrowserConfigurationDto>(), Arg.Any<CancellationToken>())
.Returns(Result.From("themed-html"));
// Act
IViewComponentResult result = await _sut.InvokeAsync();
// Assert
ViewViewComponentResult viewResult = Assert.IsType<ViewViewComponentResult>(result);
Assert.Equal("Themed", viewResult.ViewName);
Assert.Equal("themed-html", viewResult.ViewData.Model);
}
[Fact]
public async Task InvokeAsync_WhenThemedRenderFails_ShouldReturnFallbackView()
{
// Arrange
_mockRenderer.RenderAsync(Arg.Any<ThemeFileSystemBrowserConfigurationDto>(), Arg.Any<CancellationToken>())
.Returns(Error.NotFound("Theme.Template.Unavailable", "The file system browser theme template could not be loaded."));
// Act
IViewComponentResult result = await _sut.InvokeAsync();
// Assert
ViewViewComponentResult viewResult = Assert.IsType<ViewViewComponentResult>(result);
Assert.NotNull(viewResult.ViewData);
Assert.NotNull(viewResult.ViewData!.Model);
dynamic model = viewResult.ViewData!.Model!;
Assert.Equal("/", (string)model.Path);
Assert.Equal("list", (string)model.ViewMode);
Assert.Equal("large", (string)model.IconSize);
}
[Fact]
public async Task InvokeAsync_WhenCalled_ShouldPassConfigurationToRenderer()
{
// Arrange
_mockRenderer.RenderAsync(Arg.Any<ThemeFileSystemBrowserConfigurationDto>(), Arg.Any<CancellationToken>())
.Returns(Result.From("themed-html"));
// Act
await _sut.InvokeAsync();
// Assert
await _mockRenderer.Received(1).RenderAsync(
Arg.Is<ThemeFileSystemBrowserConfigurationDto>(configuration =>
configuration.ServerBasePath == "http://localhost:5214/api/v1/" &&
configuration.ClientBasePath == "http://localhost:5012/" &&
configuration.ViewMode == "list" &&
configuration.IconSize == "large"),
Arg.Any<CancellationToken>());
}
}