#region ========================================================================= USING ===================================================================================== using Nemera.Presentation.Web.Common.Api; using Nemera.Presentation.Web.Common.DTO.Themes; using Nemera.Presentation.Web.Common.Primitives; using Nemera.Presentation.Web.Common.Routes; using Nemera.Presentation.Web.Core.Themes; using Nemera.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 Nemera.Presentation.Web.UnitTests.Core.Themes; /// /// Contains unit tests for the class. /// [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(); /// /// Initializes a new instance of the class. /// public ThemeFileSystemBrowserRendererTests() { _mockApiHttpClient = Substitute.For(); _mockHttpContextAccessor = Substitute.For(); _mockStringLocalizer = CreateLocalizer(); _mockStringLocalizerFactory = Substitute.For(); _mockStringLocalizerFactory.Create(Arg.Any(), Arg.Any()).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: "
{{assetBase}}|{{iconBaseUrl}}|{{fileIconsUrl}}|{{strings.cancel}}
", treeNodeTemplate: "
{{name}}
", explorerItemTemplate: "
{{name}}
", pathSegmentTemplate: "
  • {{path}}
  • "); ThemeFileSystemBrowserConfigurationDto configuration = _themeFileSystemBrowserConfigurationDtoFixture.Create(path: "C:\\Users\\", viewMode: "list", iconSize: "large"); // Act Result 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: "", treeNodeTemplate: "not-returned", explorerItemTemplate: "not-returned", pathSegmentTemplate: "not-returned"); StubSubTemplateFailure(theme.ThemeId, "shared/file-system-browser/tree-node"); ThemeFileSystemBrowserConfigurationDto configuration = _themeFileSystemBrowserConfigurationDtoFixture.Create(); // Act Result result = await _sut.RenderAsync(configuration, CancellationToken.None); // Assert Assert.True(result.IsSuccess); Assert.Contains("", result.Value); } [Fact] public async Task RenderAsync_WhenShellDocumentCannotBeLoaded_ShouldReturnTemplateUnavailableError() { // Arrange _mockApiHttpClient.GetAsync(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any()) .Returns(Task.FromException(new HttpRequestException("The theme API is unavailable."))); ThemeFileSystemBrowserConfigurationDto configuration = _themeFileSystemBrowserConfigurationDtoFixture.Create(); // Act Result 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 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(endpoint, Arg.Any()); } } [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 result = await _sut.RenderAsync(configuration, CancellationToken.None); // Assert Assert.True(result.IsSuccess); Assert.Contains(@"C:\\Users\\", result.Value); } /// /// Creates a substitute string localizer that returns a string prefixed with "Localized-". /// /// The created substitute string localizer. private static IStringLocalizer CreateLocalizer() { IStringLocalizer localizer = Substitute.For(); localizer[Arg.Any()].Returns(callInfo => new LocalizedString(callInfo.Arg(), $"Localized-{callInfo.Arg()}")); return localizer; } /// /// Stubs the API responses that return the component shell and sub templates of the given theme, together with the current theme. /// /// The theme whose templates are stubbed. /// The template returned for the component shell document. /// The template returned for the tree node document. /// The template returned for the explorer item document. /// The template returned for the path segment document. private void SetupRenderDocuments(ThemeResponseDto theme, string shellTemplate, string treeNodeTemplate, string explorerItemTemplate, string pathSegmentTemplate) { _mockApiHttpClient.GetAsync(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any()) .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); } /// /// Stubs the API response that returns a single theme template document. /// /// The manifest id of the theme. /// The page key of the template. /// The template returned for the document. private void StubTemplateResponse(string themeId, string pageKey, string template) { string endpoint = ApiRoutes.Themes.GET_THEME_TEMPLATE .Replace("{themeId}", themeId) .Replace("{*pageKey}", pageKey); _mockApiHttpClient.GetAsync(endpoint, Arg.Any()) .Returns(_themeTemplateResponseDtoFixture.Create(theme: _themeResponseDtoFixture.Create(themeId: themeId), template: template)); } /// /// Stubs the API response of a theme template document to fail, as when the theme does not provide the template. /// /// The manifest id of the theme. /// The page key of the template. private void StubSubTemplateFailure(string themeId, string pageKey) { string endpoint = ApiRoutes.Themes.GET_THEME_TEMPLATE .Replace("{themeId}", themeId) .Replace("{*pageKey}", pageKey); _mockApiHttpClient.GetAsync(endpoint, Arg.Any()) .Returns(Task.FromException(new HttpRequestException("The sub template is unavailable."))); } }