mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 07:11:10 +00:00
Renames project paths from Lumina to Nemera
This commit is contained in:
1 parent
ce6fddb4c9
commit
0f659a4877
6450 files changed
No files matched your search
+161
@@ -0,0 +1,161 @@
|
||||
#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.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Themes;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ThemeAudioPlayerBuilder"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ThemeAudioPlayerBuilderTests
|
||||
{
|
||||
private readonly IStringLocalizerFactory _mockStringLocalizerFactory;
|
||||
private readonly IStringLocalizer _mockStringLocalizer;
|
||||
private readonly IHttpContextAccessor _mockHttpContextAccessor;
|
||||
private readonly ThemeAudioPlayerBuilder _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ThemeAudioPlayerBuilderTests"/> class.
|
||||
/// </summary>
|
||||
public ThemeAudioPlayerBuilderTests()
|
||||
{
|
||||
_mockStringLocalizer = CreateLocalizer();
|
||||
_mockStringLocalizerFactory = Substitute.For<IStringLocalizerFactory>();
|
||||
_mockStringLocalizerFactory.Create(Arg.Any<string>(), Arg.Any<string>()).Returns(_mockStringLocalizer);
|
||||
_mockHttpContextAccessor = Substitute.For<IHttpContextAccessor>();
|
||||
_sut = new ThemeAudioPlayerBuilder(_mockStringLocalizerFactory, _mockHttpContextAccessor);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenCalled_ShouldRequestTheLayoutResourcesFromTheWebAssembly()
|
||||
{
|
||||
// Arrange
|
||||
_mockStringLocalizerFactory.ClearReceivedCalls();
|
||||
|
||||
// Act
|
||||
_ = new ThemeAudioPlayerBuilder(_mockStringLocalizerFactory, _mockHttpContextAccessor);
|
||||
|
||||
// Assert
|
||||
_mockStringLocalizerFactory.Received(1).Create("Lumina.Presentation.Web.Views.Shared._Layout", "Lumina.Presentation.Web");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("toggleExpanded", "ToggleExpanded")] // The expanded player toggle.
|
||||
[InlineData("previous", "AudioPlayerPrevious")] // The previous track control.
|
||||
[InlineData("next", "AudioPlayerNext")] // The next track control.
|
||||
[InlineData("stop", "AudioPlayerStop")] // The stop control.
|
||||
[InlineData("repeat", "AudioPlayerRepeat")] // The repeat control.
|
||||
[InlineData("repeatOff", "AudioPlayerRepeatOff")] // Repeat turned off.
|
||||
[InlineData("repeatAll", "AudioPlayerRepeatAll")] // Repeat of the whole queue.
|
||||
[InlineData("repeatOne", "AudioPlayerRepeatOne")] // Repeat of a single track.
|
||||
[InlineData("queue", "AudioPlayerQueue")] // The play queue title.
|
||||
[InlineData("albumArtwork", "AudioPlayerAlbumArtwork")] // The album artwork placeholder.
|
||||
[InlineData("addQueueToPlaylist", "AudioPlayerAddQueueToPlaylist")] // Adding the queue to a playlist.
|
||||
[InlineData("addToPlaylist", "PlaylistAddToPlaylist")] // Adding a single track to a playlist.
|
||||
[InlineData("selectPlaylist", "AudioPlayerSelectPlaylist")] // The playlist selector.
|
||||
[InlineData("noPlaylists", "AudioPlayerNoPlaylists")] // No saved playlist is available.
|
||||
[InlineData("add", "AudioPlayerAdd")] // The add confirmation.
|
||||
[InlineData("playlistQueueAdded", "AudioPlayerPlaylistQueueAdded")] // The queue was added to a playlist.
|
||||
[InlineData("playlistQueueAddFailed", "AudioPlayerPlaylistQueueAddFailed")] // Adding the queue to a playlist failed.
|
||||
public void Build_WhenCalled_ShouldLocalizeThePlayerString(string modelKey, string resourceKey)
|
||||
{
|
||||
// Act
|
||||
ThemeAudioPlayerDto model = _sut.Build("/theme-assets/editorial/assets", string.Empty, string.Empty);
|
||||
|
||||
// Assert
|
||||
Assert.True(model.Strings.TryGetValue(modelKey, out object? value), $"The '{modelKey}' string is missing.");
|
||||
Assert.Equal($"Localized-{resourceKey}", Assert.IsType<string>(value));
|
||||
_ = _mockStringLocalizer.Received(1)[resourceKey];
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Build_WhenCalled_ShouldPassThroughTheAssetBaseAndTheSubTemplates()
|
||||
{
|
||||
// Arrange
|
||||
string queueItemTemplate = "<li class=\"queue-item\">{{title}}</li>";
|
||||
string playlistItemTemplate = "<li class=\"playlist-item\">{{name}}</li>";
|
||||
|
||||
// Act
|
||||
ThemeAudioPlayerDto model = _sut.Build("/theme-assets/editorial/assets", queueItemTemplate, playlistItemTemplate);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("/theme-assets/editorial/assets", model.AssetBase);
|
||||
Assert.Equal(queueItemTemplate, model.QueueItemTemplate);
|
||||
Assert.Equal(playlistItemTemplate, model.PlaylistItemTemplate);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Build_WhenSubTemplatesAreEmpty_ShouldPreserveThemUnchanged()
|
||||
{
|
||||
// Act
|
||||
ThemeAudioPlayerDto model = _sut.Build("/theme-assets/editorial/assets", string.Empty, string.Empty);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(string.Empty, model.QueueItemTemplate);
|
||||
Assert.Equal(string.Empty, model.PlaylistItemTemplate);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Build_WhenRequestHasAPathBase_ShouldResolveAppBaseWithATrailingSlash()
|
||||
{
|
||||
// Arrange
|
||||
DefaultHttpContext httpContext = TestHttpContextFactory.Create();
|
||||
httpContext.Request.Scheme = "https";
|
||||
httpContext.Request.Host = new HostString("localhost", 5001);
|
||||
httpContext.Request.PathBase = new PathString("/lumina");
|
||||
_mockHttpContextAccessor.HttpContext.Returns(httpContext);
|
||||
|
||||
// Act
|
||||
ThemeAudioPlayerDto model = _sut.Build("/theme-assets/editorial/assets", string.Empty, string.Empty);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("https://localhost:5001/lumina/", model.AppBase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Build_WhenRequestHasNoPathBase_ShouldResolveAppBaseWithATrailingSlash()
|
||||
{
|
||||
// Arrange
|
||||
DefaultHttpContext httpContext = TestHttpContextFactory.Create();
|
||||
httpContext.Request.Scheme = "https";
|
||||
httpContext.Request.Host = new HostString("localhost", 5001);
|
||||
_mockHttpContextAccessor.HttpContext.Returns(httpContext);
|
||||
|
||||
// Act
|
||||
ThemeAudioPlayerDto model = _sut.Build("/theme-assets/editorial/assets", string.Empty, string.Empty);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("https://localhost:5001/", model.AppBase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Build_WhenRequestIsUnavailable_ShouldReturnAnEmptyAppBase()
|
||||
{
|
||||
// Arrange
|
||||
_mockHttpContextAccessor.HttpContext.Returns((HttpContext?)null);
|
||||
|
||||
// Act
|
||||
ThemeAudioPlayerDto model = _sut.Build("/theme-assets/editorial/assets", 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;
|
||||
}
|
||||
}
|
||||
+281
@@ -0,0 +1,281 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.Themes;
|
||||
using Lumina.Presentation.Web.Common.Enums.Primitives;
|
||||
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="ThemeAudioPlayerRenderer"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ThemeAudioPlayerRendererTests
|
||||
{
|
||||
private const string THEME_ID = "editorial";
|
||||
private const string SHELL_PAGE_KEY = "shared/audio-player";
|
||||
private const string QUEUE_ITEM_PAGE_KEY = "shared/audio-player/queue-item";
|
||||
private const string PLAYLIST_ITEM_PAGE_KEY = "shared/audio-player/playlist-item";
|
||||
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly IHttpContextAccessor _mockHttpContextAccessor;
|
||||
private readonly IStringLocalizerFactory _mockStringLocalizerFactory;
|
||||
private readonly IStringLocalizer _mockStringLocalizer;
|
||||
private readonly ThemeAudioPlayerRenderer _sut;
|
||||
private readonly ThemeResponseDtoFixture _themeResponseDtoFixture = new();
|
||||
private readonly ThemeTemplateResponseDtoFixture _themeTemplateResponseDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ThemeAudioPlayerRendererTests"/> class.
|
||||
/// </summary>
|
||||
public ThemeAudioPlayerRendererTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_mockStringLocalizer = CreateLocalizer();
|
||||
_mockStringLocalizerFactory = Substitute.For<IStringLocalizerFactory>();
|
||||
_mockStringLocalizerFactory.Create(Arg.Any<string>(), Arg.Any<string>()).Returns(_mockStringLocalizer);
|
||||
_mockHttpContextAccessor = Substitute.For<IHttpContextAccessor>();
|
||||
ThemeService themeService = new(_mockApiHttpClient);
|
||||
ThemeAudioPlayerBuilder builder = new(_mockStringLocalizerFactory, _mockHttpContextAccessor);
|
||||
_sut = new ThemeAudioPlayerRenderer(themeService, new ThemeTemplateEngine(), builder);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RenderAsync_WhenCalled_ShouldRenderTheShellWithTheThemeAssetBaseAndThePlayerModel()
|
||||
{
|
||||
// Arrange
|
||||
StubTemplate(THEME_ID, SHELL_PAGE_KEY, "<div class=\"lumina-audio-player\" data-asset-base=\"{{{assetBase}}}\" data-queue-label=\"{{strings.queue}}\"></div>");
|
||||
StubTemplate(THEME_ID, QUEUE_ITEM_PAGE_KEY, string.Empty);
|
||||
StubTemplate(THEME_ID, PLAYLIST_ITEM_PAGE_KEY, string.Empty);
|
||||
|
||||
// Act
|
||||
Result<string> result = await _sut.RenderAsync(THEME_ID, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Contains("/theme-assets/editorial/assets", result.Value);
|
||||
Assert.Contains("data-queue-label=\"Localized-AudioPlayerQueue\"", result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RenderAsync_WhenThemeProvidesSubTemplates_ShouldInlineThemInTheShell()
|
||||
{
|
||||
// Arrange
|
||||
StubTemplate(THEME_ID, SHELL_PAGE_KEY, "{{{queueItemTemplate}}}|{{{playlistItemTemplate}}}");
|
||||
StubTemplate(THEME_ID, QUEUE_ITEM_PAGE_KEY, "<li class=\"queue-item\">{{title}}</li>");
|
||||
StubTemplate(THEME_ID, PLAYLIST_ITEM_PAGE_KEY, "<li class=\"playlist-item\">{{name}}</li>");
|
||||
|
||||
// Act
|
||||
Result<string> result = await _sut.RenderAsync(THEME_ID, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal("<li class=\"queue-item\">{{title}}</li>|<li class=\"playlist-item\">{{name}}</li>", result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RenderAsync_WhenSubTemplateIsMissing_ShouldInlineAnEmptySubTemplate()
|
||||
{
|
||||
// Arrange
|
||||
StubTemplate(THEME_ID, SHELL_PAGE_KEY, "{{{queueItemTemplate}}}|{{{playlistItemTemplate}}}");
|
||||
StubTemplateFailure(THEME_ID, QUEUE_ITEM_PAGE_KEY, new HttpRequestException("The sub template is unavailable."));
|
||||
StubTemplate(THEME_ID, PLAYLIST_ITEM_PAGE_KEY, string.Empty);
|
||||
|
||||
// Act
|
||||
Result<string> result = await _sut.RenderAsync(THEME_ID, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal("|", result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RenderAsync_WhenSubTemplateResolvesToTheShellTemplate_ShouldInlineAnEmptySubTemplate()
|
||||
{
|
||||
// Arrange
|
||||
string shellTemplate = "<div class=\"lumina-audio-player\">{{{queueItemTemplate}}}|{{{playlistItemTemplate}}}</div>";
|
||||
StubTemplate(THEME_ID, SHELL_PAGE_KEY, shellTemplate);
|
||||
StubTemplate(THEME_ID, QUEUE_ITEM_PAGE_KEY, shellTemplate);
|
||||
StubTemplate(THEME_ID, PLAYLIST_ITEM_PAGE_KEY, shellTemplate);
|
||||
|
||||
// Act
|
||||
Result<string> result = await _sut.RenderAsync(THEME_ID, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal("<div class=\"lumina-audio-player\">|</div>", result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RenderAsync_WhenTemplateDefinesScripts_ShouldConcatenateTheContentAndTheScript()
|
||||
{
|
||||
// Arrange
|
||||
StubTemplate(THEME_ID, SHELL_PAGE_KEY, "<div>content</div>{{#scripts}}<script>init();</script>{{/scripts}}");
|
||||
StubTemplate(THEME_ID, QUEUE_ITEM_PAGE_KEY, string.Empty);
|
||||
StubTemplate(THEME_ID, PLAYLIST_ITEM_PAGE_KEY, string.Empty);
|
||||
|
||||
// Act
|
||||
Result<string> result = await _sut.RenderAsync(THEME_ID, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal("<div>content</div><script>init();</script>", result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RenderAsync_WhenTemplateEngineFails_ShouldReturnTheTemplateErrors()
|
||||
{
|
||||
// Arrange
|
||||
StubTemplate(THEME_ID, SHELL_PAGE_KEY, "{{#unclosed}}");
|
||||
StubTemplate(THEME_ID, QUEUE_ITEM_PAGE_KEY, string.Empty);
|
||||
StubTemplate(THEME_ID, PLAYLIST_ITEM_PAGE_KEY, string.Empty);
|
||||
|
||||
// Act
|
||||
Result<string> result = await _sut.RenderAsync(THEME_ID, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal("Theme.Template.Invalid", result.FirstError.Code);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RenderAsync_WhenShellDocumentCannotBeLoaded_ShouldReturnTemplateUnavailableError()
|
||||
{
|
||||
// Arrange
|
||||
StubTemplateFailure(THEME_ID, SHELL_PAGE_KEY, new HttpRequestException("The theme API is unavailable."));
|
||||
|
||||
// Act
|
||||
Result<string> result = await _sut.RenderAsync(THEME_ID, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal("Theme.Template.Unavailable", result.FirstError.Code);
|
||||
Assert.Equal(ErrorType.NotFound, result.FirstError.Type);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RenderAsync_WhenShellTemplateCannotBeRendered_ShouldReturnTemplateUnavailableError()
|
||||
{
|
||||
// Arrange
|
||||
StubTemplate(THEME_ID, SHELL_PAGE_KEY, string.Empty, includeTemplate: false);
|
||||
StubTemplate(THEME_ID, QUEUE_ITEM_PAGE_KEY, string.Empty);
|
||||
StubTemplate(THEME_ID, PLAYLIST_ITEM_PAGE_KEY, string.Empty);
|
||||
|
||||
// Act
|
||||
Result<string> result = await _sut.RenderAsync(THEME_ID, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal("Theme.Template.Unavailable", result.FirstError.Code);
|
||||
Assert.Equal(ErrorType.NotFound, result.FirstError.Type);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RenderAsync_WhenShellLoadIsCancelled_ShouldRethrowTheCancellation()
|
||||
{
|
||||
// Arrange
|
||||
StubTemplateFailure(THEME_ID, SHELL_PAGE_KEY, new OperationCanceledException());
|
||||
|
||||
// Act
|
||||
Task<Result<string>> operationTask = _sut.RenderAsync(THEME_ID, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RenderAsync_WhenSubTemplateLoadIsCancelled_ShouldRethrowTheCancellation()
|
||||
{
|
||||
// Arrange
|
||||
StubTemplate(THEME_ID, SHELL_PAGE_KEY, "<div>{{{queueItemTemplate}}}</div>");
|
||||
StubTemplateFailure(THEME_ID, QUEUE_ITEM_PAGE_KEY, new OperationCanceledException());
|
||||
StubTemplate(THEME_ID, PLAYLIST_ITEM_PAGE_KEY, string.Empty);
|
||||
|
||||
// Act
|
||||
Task<Result<string>> operationTask = _sut.RenderAsync(THEME_ID, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RenderAsync_WhenCalled_ShouldPassTheThemeIdAndTheCancellationTokenToTheTemplateLookups()
|
||||
{
|
||||
// Arrange
|
||||
using CancellationTokenSource cancellationTokenSource = new();
|
||||
StubTemplate(THEME_ID, SHELL_PAGE_KEY, "shell");
|
||||
StubTemplate(THEME_ID, QUEUE_ITEM_PAGE_KEY, "queue");
|
||||
StubTemplate(THEME_ID, PLAYLIST_ITEM_PAGE_KEY, "playlist");
|
||||
|
||||
// Act
|
||||
await _sut.RenderAsync(THEME_ID, cancellationTokenSource.Token);
|
||||
|
||||
// Assert
|
||||
string[] pageKeys = [SHELL_PAGE_KEY, QUEUE_ITEM_PAGE_KEY, PLAYLIST_ITEM_PAGE_KEY];
|
||||
foreach (string pageKey in pageKeys)
|
||||
{
|
||||
string endpoint = ApiRoutes.Themes.GET_THEME_TEMPLATE
|
||||
.Replace("{themeId}", THEME_ID)
|
||||
.Replace("{*pageKey}", pageKey);
|
||||
await _mockApiHttpClient.Received(1).GetAsync<ThemeTemplateResponseDto>(endpoint, Arg.Is(cancellationTokenSource.Token));
|
||||
}
|
||||
await _mockApiHttpClient.DidNotReceive().GetAsync<ThemeResponseDto>(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the API response that returns a single audio player 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>
|
||||
/// <param name="includeTemplate">Whether the returned document has a template, or a <see langword="null"/> one.</param>
|
||||
private void StubTemplate(string themeId, string pageKey, string template, bool includeTemplate = true)
|
||||
{
|
||||
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,
|
||||
includeTemplate: includeTemplate));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the API response of an audio player template document to fail.
|
||||
/// </summary>
|
||||
/// <param name="themeId">The manifest id of the theme.</param>
|
||||
/// <param name="pageKey">The page key of the template.</param>
|
||||
/// <param name="exception">The exception the API call throws.</param>
|
||||
private void StubTemplateFailure(string themeId, string pageKey, Exception exception)
|
||||
{
|
||||
string endpoint = ApiRoutes.Themes.GET_THEME_TEMPLATE
|
||||
.Replace("{themeId}", themeId)
|
||||
.Replace("{*pageKey}", pageKey);
|
||||
_mockApiHttpClient.GetAsync<ThemeTemplateResponseDto>(endpoint, Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromException<ThemeTemplateResponseDto>(exception));
|
||||
}
|
||||
|
||||
/// <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;
|
||||
}
|
||||
}
|
||||
+123
@@ -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;
|
||||
}
|
||||
}
|
||||
+231
@@ -0,0 +1,231 @@
|
||||
#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);
|
||||
}
|
||||
|
||||
[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.")));
|
||||
}
|
||||
}
|
||||
+280
@@ -0,0 +1,280 @@
|
||||
#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.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.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="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 _mockServerUnreachableBannerView;
|
||||
private readonly IView _mockScriptsView;
|
||||
private readonly IView _mockNavMenuView;
|
||||
private readonly ThemeResponseDtoFixture _themeResponseDtoFixture = new();
|
||||
private readonly ThemeTemplateResponseDtoFixture _themeTemplateResponseDtoFixture = new();
|
||||
private readonly ThemeLayoutPageDtoFixture _themeLayoutPageDtoFixture = new();
|
||||
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>");
|
||||
_mockServerUnreachableBannerView = CreateView("<banner-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>(), "_ServerUnreachableBanner", false).Returns(ViewEngineResult.Found("_ServerUnreachableBanner", _mockServerUnreachableBannerView));
|
||||
_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);
|
||||
ThemeAudioPlayerBuilder audioPlayerBuilder = new(_mockStringLocalizerFactory, _mockHttpContextAccessor);
|
||||
ThemeAudioPlayerRenderer audioPlayerRenderer = new(themeService, new ThemeTemplateEngine(), audioPlayerBuilder);
|
||||
_sut = new ThemeLayoutRenderer(themeService, new ThemeTemplateEngine(), viewRenderer, navBuilder, audioPlayerRenderer, _mockHttpContextAccessor, _mockStringLocalizerFactory);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RenderAsync_WhenUserIsAuthenticated_ShouldRenderLayoutWithAllPlaceholders()
|
||||
{
|
||||
// Arrange
|
||||
_mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(user: TestHttpContextFactory.CreateAuthenticatedUser()));
|
||||
ThemeResponseDto theme = _themeResponseDtoFixture.Create(themeId: "editorial");
|
||||
SetupRenderDocuments(theme, layoutTemplate: "{{title}}|{{assetBase}}|{{{appHead}}}|{{{nav}}}|{{{content}}}|{{{audioPlayer}}}|{{{appScripts}}}|{{{scripts}}}|{{mainStyle}}", navTemplate: "nav:{{siteName}}");
|
||||
ThemeLayoutPageDto page = _themeLayoutPageDtoFixture.Create(title: "My Page", content: "<main>", script: "<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 = _themeResponseDtoFixture.Create(themeId: "editorial");
|
||||
SetupRenderDocuments(theme, layoutTemplate: "{{title}}|{{assetBase}}|{{{appHead}}}|{{{nav}}}|{{{content}}}|{{{audioPlayer}}}|{{{appScripts}}}|{{{scripts}}}|{{mainStyle}}", navTemplate: "nav:{{siteName}}");
|
||||
ThemeLayoutPageDto page = _themeLayoutPageDtoFixture.Create(title: "My Page", content: "<main>", script: "<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 = _themeResponseDtoFixture.Create(themeId: "editorial");
|
||||
SetupRenderDocuments(theme, layoutTemplate: "{{title}}|{{{nav}}}", navTemplate: "{{#unclosed}}");
|
||||
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_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()
|
||||
{
|
||||
// Arrange
|
||||
_mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(user: null));
|
||||
ThemeResponseDto theme = _themeResponseDtoFixture.Create(themeId: "editorial");
|
||||
SetupRenderDocuments(theme, layoutTemplate: "{{title}}", navTemplate: "nav:{{siteName}}");
|
||||
ThemeLayoutPageDto page = _themeLayoutPageDtoFixture.Create(title: "My Page", content: "<main>", script: 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>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RenderAsync_WhenThemeProvidesServerUnreachableBannerTemplate_ShouldRenderItInTheLayout()
|
||||
{
|
||||
// Arrange
|
||||
_mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(user: null));
|
||||
ThemeResponseDto theme = _themeResponseDtoFixture.Create(themeId: "editorial-banner");
|
||||
SetupRenderDocuments(theme, layoutTemplate: "{{title}}|{{{serverUnreachableBanner}}}", navTemplate: "nav:{{siteName}}");
|
||||
string bannerEndpoint = ApiRoutes.Themes.GET_THEME_TEMPLATE
|
||||
.Replace("{themeId}", "editorial-banner")
|
||||
.Replace("{*pageKey}", "shared/server-unreachable-banner");
|
||||
_mockApiHttpClient.GetAsync<ThemeTemplateResponseDto>(bannerEndpoint, Arg.Any<CancellationToken>())
|
||||
.Returns(_themeTemplateResponseDtoFixture.Create(theme: theme, template: "banner:{{message}}"));
|
||||
ThemeLayoutPageDto page = _themeLayoutPageDtoFixture.Create(title: "My Page", content: "<main>", script: string.Empty);
|
||||
|
||||
// Act
|
||||
Result<string> result = await _sut.RenderAsync(page, "editorial-banner", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal("My Page|banner:Localized-ServerUnreachable", result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RenderAsync_WhenThemeDoesNotProvideServerUnreachableBannerTemplate_ShouldRenderTheApplicationFallback()
|
||||
{
|
||||
// Arrange
|
||||
_mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(user: null));
|
||||
ThemeResponseDto theme = _themeResponseDtoFixture.Create(themeId: "editorial-without-banner");
|
||||
SetupRenderDocuments(theme, layoutTemplate: "{{title}}|{{{serverUnreachableBanner}}}", navTemplate: "nav:{{siteName}}");
|
||||
ThemeLayoutPageDto page = _themeLayoutPageDtoFixture.Create(title: "My Page", content: "<main>", script: string.Empty);
|
||||
|
||||
// Act
|
||||
Result<string> result = await _sut.RenderAsync(page, "editorial-without-banner", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal("My Page|<banner-fragment>", result.Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the API responses that return the layout and navigation menu templates of the given theme.
|
||||
/// </summary>
|
||||
/// <param name="theme">The theme whose layout and navigation menu templates are stubbed.</param>
|
||||
/// <param name="layoutTemplate">The template returned for the layout document.</param>
|
||||
/// <param name="navTemplate">The template returned for the navigation menu document.</param>
|
||||
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(_themeTemplateResponseDtoFixture.Create(theme: theme, template: layoutTemplate));
|
||||
_mockApiHttpClient.GetAsync<ThemeTemplateResponseDto>(navEndpoint, Arg.Any<CancellationToken>())
|
||||
.Returns(_themeTemplateResponseDtoFixture.Create(theme: theme, template: navTemplate));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a substitute view that renders the given markup.
|
||||
/// </summary>
|
||||
/// <param name="markup">The markup rendered by the view.</param>
|
||||
/// <returns>The created substitute view.</returns>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <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;
|
||||
}
|
||||
}
|
||||
+332
@@ -0,0 +1,332 @@
|
||||
#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_WhenUserIsAuthenticated_ShouldLinkWrittenContentAndAudioEntriesToTheFilteredLibraryCatalog()
|
||||
{
|
||||
// Arrange
|
||||
_mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(user: TestHttpContextFactory.CreateAuthenticatedUser()));
|
||||
|
||||
// Act
|
||||
ThemeNavMenuDto result = await _sut.BuildAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// The written content and audio entries open the home page filtered to the libraries of their category, so that browsing starts
|
||||
// from the libraries of that category, instead of from a single library picked upfront.
|
||||
ThemeNavSectionDto librarySection = FindSection(result, "Localized-Library")!;
|
||||
ThemeNavEntryDto writtenContentEntry = librarySection.Items.First(entry => entry.Label == "Localized-WrittenContent");
|
||||
ThemeNavEntryDto audioEntry = librarySection.Items.First(entry => entry.Label == "Localized-Audio");
|
||||
Assert.Contains(writtenContentEntry.Children, entry => entry.Label == "Localized-Books" && entry.Url == "http://localhost/en-us?category=books");
|
||||
Assert.Contains(writtenContentEntry.Children, entry => entry.Label == "Localized-Magazines" && entry.Url == "library/written-content/magazines");
|
||||
Assert.Contains(audioEntry.Children, entry => entry.Label == "Localized-Music" && entry.Url == "http://localhost/en-us?category=music");
|
||||
Assert.Contains(audioEntry.Children, entry => entry.Label == "Localized-Interviews" && entry.Url == "library/audio/interviews");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task BuildAsync_WhenUserIsAuthenticated_ShouldIncludeFavoritesEntryInTheLibrarySection()
|
||||
{
|
||||
// Arrange
|
||||
_mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(user: TestHttpContextFactory.CreateAuthenticatedUser()));
|
||||
|
||||
// Act
|
||||
ThemeNavMenuDto result = await _sut.BuildAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
ThemeNavSectionDto mobileLibrarySection = FindSection(result, "Localized-Library")!;
|
||||
Assert.Contains(mobileLibrarySection.Items, entry => entry.Label == "Localized-Favorites" && entry.Url == "http://localhost/en-us/favorites");
|
||||
ThemeNavSectionDto menubarLibrarySection = FindSection(result, "Localized-Library", isMobile: false)!;
|
||||
Assert.Contains(menubarLibrarySection.Items, entry => entry.Label == "Localized-Favorites" && entry.Url == "http://localhost/en-us/favorites");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task BuildAsync_WhenUserIsAnonymous_ShouldNotIncludeAnyFavoritesEntry()
|
||||
{
|
||||
// Arrange
|
||||
_mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(user: null));
|
||||
|
||||
// Act
|
||||
ThemeNavMenuDto result = await _sut.BuildAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.DoesNotContain(FlattenEntries(result.MobileSections), entry => entry.Label == "Localized-Favorites");
|
||||
Assert.DoesNotContain(FlattenEntries(result.MenubarSections), entry => entry.Label == "Localized-Favorites");
|
||||
Assert.DoesNotContain(FlattenEntries(result.MobileSections), entry => entry.Url == "http://localhost/en-us/favorites");
|
||||
Assert.DoesNotContain(FlattenEntries(result.MenubarSections), entry => entry.Url == "http://localhost/en-us/favorites");
|
||||
}
|
||||
|
||||
[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(10, 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 == 10);
|
||||
}
|
||||
|
||||
[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.Favorites.INDEX).Returns("http://localhost/en-us/favorites");
|
||||
_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");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Flattens the entries of the given sections, including the nested children of every submenu.
|
||||
/// </summary>
|
||||
/// <param name="sections">The sections whose entries are flattened.</param>
|
||||
/// <returns>The entries of the sections, depth first.</returns>
|
||||
private static IEnumerable<ThemeNavEntryDto> FlattenEntries(IEnumerable<ThemeNavSectionDto> sections)
|
||||
{
|
||||
foreach (ThemeNavSectionDto section in sections)
|
||||
foreach (ThemeNavEntryDto entry in FlattenEntries(section.Items))
|
||||
yield return entry;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Flattens the given entries, including the nested children of every submenu.
|
||||
/// </summary>
|
||||
/// <param name="entries">The entries to flatten.</param>
|
||||
/// <returns>The entries, depth first.</returns>
|
||||
private static IEnumerable<ThemeNavEntryDto> FlattenEntries(IEnumerable<ThemeNavEntryDto> entries)
|
||||
{
|
||||
foreach (ThemeNavEntryDto entry in entries)
|
||||
{
|
||||
yield return entry;
|
||||
foreach (ThemeNavEntryDto child in FlattenEntries(entry.Children))
|
||||
yield return child;
|
||||
}
|
||||
}
|
||||
|
||||
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.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();
|
||||
private readonly ThemeTemplateResponseDtoFixture _themeTemplateResponseDtoFixture = 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(_themeTemplateResponseDtoFixture.Create(theme: theme, template: 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(_themeTemplateResponseDtoFixture.Create(theme: currentTheme, template: "{{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(_themeTemplateResponseDtoFixture.Create(theme: theme, template: "{{#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,246 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.Themes;
|
||||
using Lumina.Presentation.Web.Common.Enums.Themes;
|
||||
using Lumina.Presentation.Web.Common.Requests.Themes;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Themes;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes;
|
||||
using NSubstitute;
|
||||
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();
|
||||
private readonly BlobDataDtoFixture _blobDataDtoFixture = 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);
|
||||
_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.PutIgnoringResponseAsync<SetCurrentThemeRequest>(Arg.Any<string>(), Arg.Any<SetCurrentThemeRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
// Act
|
||||
await _sut.SetCurrentThemeAsync(themeId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutIgnoringResponseAsync<SetCurrentThemeRequest>(
|
||||
ApiRoutes.Themes.SET_CURRENT_THEME,
|
||||
Arg.Is<SetCurrentThemeRequest>(payload => payload.ThemeId == 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(_blobDataDtoFixture.Create(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>());
|
||||
}
|
||||
}
|
||||
+535
@@ -0,0 +1,535 @@
|
||||
#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.DTO.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();
|
||||
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.
|
||||
/// </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_WhenMenuEntryHasChildren_ShouldRenderEntryLabelOnceWithNestedChildren()
|
||||
{
|
||||
// Arrange
|
||||
ThemeNavMenuDto model = _themeNavMenuDtoFixture.Create(
|
||||
siteName: "Lumina",
|
||||
mobileSections: [],
|
||||
menubarSections:
|
||||
[
|
||||
_themeNavSectionDtoFixture.Create(
|
||||
label: "Tools",
|
||||
items:
|
||||
[
|
||||
_themeNavEntryDtoFixture.Create(
|
||||
label: "Language",
|
||||
includeUrl: false,
|
||||
children:
|
||||
[
|
||||
_themeNavEntryDtoFixture.Create(label: "English", includeUrl: true, url: "/en", cssClass: "lang-set", includeCssClass: true),
|
||||
_themeNavEntryDtoFixture.Create(label: "Francais", includeUrl: true, url: "/fr", cssClass: "lang-set", includeCssClass: true)
|
||||
]),
|
||||
_themeNavEntryDtoFixture.Create(label: "Settings", includeUrl: true, url: "/settings", cssClass: "nav-link", includeCssClass: true)
|
||||
])
|
||||
]);
|
||||
string template = "{{#menubarSections}}{{label}}:{{#items}}{{#isSubmenu}}[{{label}}]{{#children}}{{label}},{{/children}}{{/isSubmenu}}{{^isSubmenu}}{{label}}{{/isSubmenu}}{{/items}}{{/menubarSections}}";
|
||||
|
||||
// Act
|
||||
Result<ThemePageRenderResultDto> result = _sut.RenderPage(template, model);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
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()
|
||||
{
|
||||
// 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