Shows a connection-lost indicator when the SignalR connection closes.

This commit is contained in:
BinaryAlley committed 2026-11-07 17:03:55 +02:00
1 parent 0abf8d4aea
commit e2c705d822
44 files changed
+1254 -78

No files matched your search

@@ -36,6 +36,12 @@ public class StubApiHttpClient : IApiHttpClient
/// </summary>
public GetAuthorizationResponse AuthorizationResponse { get; set; } = new(Guid.NewGuid(), "Admin", Enum.GetValues<AuthorizationPermission>());
/// <summary>
/// Gets or sets the exception thrown when the <c>auth/get-authorization</c> endpoint is called, or <see langword="null"/> to return
/// <see cref="AuthorizationResponse"/>. It simulates an API outage during authorization.
/// </summary>
public Exception? AuthorizationException { get; set; }
/// <summary>
/// Gets or sets the initialization response returned for the <c>initialization</c> endpoint.
/// </summary>
@@ -198,6 +204,7 @@ public class StubApiHttpClient : IApiHttpClient
_deleteSuccessEndpoints.Clear();
_deleteExceptions.Clear();
_blobResponse = null;
AuthorizationException = null;
GetEndpointsCalled.Clear();
PostRequests.Clear();
PutRequests.Clear();
@@ -219,7 +226,11 @@ public class StubApiHttpClient : IApiHttpClient
if (endpoint.StartsWith(ApiRoutes.Initialization.CHECK_INITIALIZATION, StringComparison.OrdinalIgnoreCase))
return Task.FromResult((TResponse)(object)InitializationResponse);
if (endpoint.Contains("auth/get-authorization", StringComparison.OrdinalIgnoreCase))
{
if (AuthorizationException is not null)
throw AuthorizationException;
return Task.FromResult((TResponse)(object)AuthorizationResponse);
}
throw new InvalidOperationException($"No GET response is registered for the endpoint '{endpoint}'.");
}
@@ -5,6 +5,7 @@ using Lumina.Presentation.Web.Fixtures.Common.DTO.Authorization;
using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
using Polly.CircuitBreaker;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
@@ -70,4 +71,28 @@ public class ManageRolesViewEndpointTests : IClassFixture<LuminaWebFactory>
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Contains("access-denied", response.Headers.Location!.ToString());
}
[Fact]
public async Task ManageRoles_WhenTheApiIsUnreachableDuringAuthorization_ShouldRenderThePage()
{
// Arrange
// The policy handler runs under real endpoint routing, where the authorization resource is the endpoint, not the HttpContext.
_apiFactory.ApiClientStub.Reset();
_apiFactory.ApiClientStub.AuthorizationException = new BrokenCircuitException();
RoleDto[] expectedRoles = [.. _roleDtoFixture.CreateMany()];
PermissionDto[] expectedPermissions = [.. _permissionDtoFixture.CreateMany()];
_apiFactory.ApiClientStub.RegisterGetResponse("auth/roles", expectedRoles);
_apiFactory.ApiClientStub.RegisterGetResponse("auth/permissions", expectedPermissions);
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
// Act
HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/manage-roles");
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType);
string content = await response.Content.ReadAsStringAsync();
Assert.Contains("data-server-unreachable-banner", content);
}
}
@@ -41,6 +41,7 @@ public class HomeErrorEndpointTests : IClassFixture<LuminaWebFactory>
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType);
string content = await response.Content.ReadAsStringAsync();
Assert.Contains("text-danger", content);
Assert.Contains("Navigation failed!", content);
Assert.Contains("data-server-unreachable-banner", content);
}
}
@@ -2,12 +2,16 @@
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Authorization;
using Lumina.Presentation.Web.Common.Enums.Authorization;
using Lumina.Presentation.Web.Common.Exceptions;
using Lumina.Presentation.Web.Common.Http;
using Lumina.Presentation.Web.Common.Responses.Authorization;
using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization;
using Microsoft.AspNetCore.Http;
using NSubstitute;
using Polly.CircuitBreaker;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
@@ -24,6 +28,7 @@ public class AuthorizationServiceTests
private readonly IApiHttpClient _mockApiHttpClient;
private readonly AuthorizationService _sut;
private readonly Guid _userId;
private readonly DefaultHttpContext _httpContext;
private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new();
/// <summary>
@@ -34,9 +39,9 @@ public class AuthorizationServiceTests
_userId = Guid.NewGuid();
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
IHttpContextAccessor httpContextAccessor = Substitute.For<IHttpContextAccessor>();
DefaultHttpContext httpContext = new();
httpContext.User = new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, _userId.ToString())], "TestAuthentication"));
httpContextAccessor.HttpContext.Returns(httpContext);
_httpContext = new DefaultHttpContext();
_httpContext.User = new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, _userId.ToString())], "TestAuthentication"));
httpContextAccessor.HttpContext.Returns(_httpContext);
_sut = new AuthorizationService(_mockApiHttpClient, httpContextAccessor);
}
@@ -111,4 +116,63 @@ public class AuthorizationServiceTests
Arg.Is<string>(endpoint => endpoint.StartsWith($"auth/get-authorization?userId={_userId}", StringComparison.OrdinalIgnoreCase)),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task HasPermissionAsync_WhenTheApiIsUnreachableDuringAPageNavigation_ShouldReturnFalseAndMarkTheServerUnreachable()
{
// Arrange
_httpContext.Request.Headers.Accept = "text/html";
_mockApiHttpClient.GetAsync<GetAuthorizationResponse>(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(Task.FromException<GetAuthorizationResponse>(new BrokenCircuitException()));
// Act
bool result = await _sut.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, CancellationToken.None);
// Assert
Assert.False(result);
Assert.True(_httpContext.Items[HttpContextItemKeys.SERVER_UNREACHABLE] is true);
}
[Fact]
public async Task HasPermissionAsync_WhenTheApiIsUnreachableDuringAJsonRequest_ShouldRethrow()
{
// Arrange
_httpContext.Request.Headers.Accept = "application/json";
_mockApiHttpClient.GetAsync<GetAuthorizationResponse>(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(Task.FromException<GetAuthorizationResponse>(new BrokenCircuitException()));
// Act & Assert
await Assert.ThrowsAsync<BrokenCircuitException>(() => _sut.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, CancellationToken.None));
}
[Theory]
[InlineData(HttpStatusCode.Unauthorized)]
[InlineData(HttpStatusCode.Forbidden)]
[InlineData(HttpStatusCode.NotFound)]
public async Task HasPermissionAsync_WhenTheApiReturnsAnAuthorizationStatusDuringAPageNavigation_ShouldRethrow(HttpStatusCode statusCode)
{
// Arrange
_httpContext.Request.Headers.Accept = "text/html";
_mockApiHttpClient.GetAsync<GetAuthorizationResponse>(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(Task.FromException<GetAuthorizationResponse>(new ApiException(null, statusCode)));
// Act & Assert
await Assert.ThrowsAsync<ApiException>(() => _sut.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, CancellationToken.None));
}
[Fact]
public async Task HasPermissionAsync_WhenTheApiReturnsAServerErrorDuringAPageNavigation_ShouldReturnFalseAndMarkTheServerUnreachable()
{
// Arrange
_httpContext.Request.Headers.Accept = "text/html";
_mockApiHttpClient.GetAsync<GetAuthorizationResponse>(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(Task.FromException<GetAuthorizationResponse>(new ApiException(null, HttpStatusCode.InternalServerError)));
// Act
bool result = await _sut.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, CancellationToken.None);
// Assert
Assert.False(result);
Assert.True(_httpContext.Items[HttpContextItemKeys.SERVER_UNREACHABLE] is true);
}
}
@@ -0,0 +1,109 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Authorization;
using Lumina.Presentation.Web.Common.Exceptions;
using Lumina.Presentation.Web.Common.Http;
using Lumina.Presentation.Web.Common.Responses.UsersManagement;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using NSubstitute;
using Polly.CircuitBreaker;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Common.Authorization;
/// <summary>
/// Contains unit tests for the <see cref="InitializationHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class InitializationHandlerTests
{
private readonly IApiHttpClient _mockApiHttpClient;
private readonly InitializationHandler _sut;
/// <summary>
/// Initializes a new instance of the <see cref="InitializationHandlerTests"/> class.
/// </summary>
public InitializationHandlerTests()
{
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
_sut = new InitializationHandler(_mockApiHttpClient);
}
[Fact]
public async Task HandleAsync_WhenTheApiIsUnreachableDuringAPageNavigation_ShouldSucceedAndMarkTheServerUnreachable()
{
// Arrange
DefaultHttpContext httpContext = CreateHttpContext();
_mockApiHttpClient.GetAsync<InitializationResponse>(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(Task.FromException<InitializationResponse>(new BrokenCircuitException()));
AuthorizationHandlerContext context = CreateContext(httpContext);
// Act
await _sut.HandleAsync(context);
// Assert
Assert.True(context.HasSucceeded);
Assert.True(httpContext.Items[HttpContextItemKeys.SERVER_UNREACHABLE] is true);
}
[Fact]
public async Task HandleAsync_WhenTheApiReturnsUnauthorizedDuringAPageNavigation_ShouldRethrow()
{
// Arrange
DefaultHttpContext httpContext = CreateHttpContext();
_mockApiHttpClient.GetAsync<InitializationResponse>(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(Task.FromException<InitializationResponse>(new ApiException(null, HttpStatusCode.Unauthorized)));
AuthorizationHandlerContext context = CreateContext(httpContext);
// Act & Assert
await Assert.ThrowsAsync<ApiException>(() => _sut.HandleAsync(context));
}
[Fact]
public async Task HandleAsync_WhenTheApiReturnsAServerErrorDuringAPageNavigation_ShouldSucceedAndMarkTheServerUnreachable()
{
// Arrange
DefaultHttpContext httpContext = CreateHttpContext();
_mockApiHttpClient.GetAsync<InitializationResponse>(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(Task.FromException<InitializationResponse>(new ApiException(null, HttpStatusCode.InternalServerError)));
AuthorizationHandlerContext context = CreateContext(httpContext);
// Act
await _sut.HandleAsync(context);
// Assert
Assert.True(context.HasSucceeded);
Assert.True(httpContext.Items[HttpContextItemKeys.SERVER_UNREACHABLE] is true);
}
/// <summary>
/// Creates a page navigation HTTP context.
/// </summary>
/// <returns>The created HTTP context.</returns>
private static DefaultHttpContext CreateHttpContext()
{
DefaultHttpContext httpContext = new();
httpContext.Request.Headers.Accept = "text/html";
return httpContext;
}
/// <summary>
/// Creates an authorization context that evaluates the initialization requirement.
/// </summary>
/// <param name="httpContext">The HTTP context of the request being authorized.</param>
/// <returns>The created authorization context.</returns>
private static AuthorizationHandlerContext CreateContext(HttpContext httpContext)
{
return new AuthorizationHandlerContext(
[new InitializationRequirement()],
new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString())], "TestAuthentication")),
httpContext);
}
}
@@ -1,8 +1,11 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Authorization;
using Lumina.Presentation.Web.Common.Enums.Authorization;
using Lumina.Presentation.Web.Common.Http;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Security.Claims;
using System.Threading;
@@ -19,6 +22,7 @@ namespace Lumina.Presentation.Web.UnitTests.Common.Authorization;
public class PermissionAuthorizationHandlerTests
{
private readonly IAuthorizationService _mockAuthorizationService;
private readonly DefaultHttpContext _httpContext;
private readonly PermissionAuthorizationHandler _sut;
/// <summary>
@@ -27,7 +31,13 @@ public class PermissionAuthorizationHandlerTests
public PermissionAuthorizationHandlerTests()
{
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_sut = new PermissionAuthorizationHandler(_mockAuthorizationService);
_httpContext = new DefaultHttpContext
{
User = new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString())], "TestAuthentication"))
};
IHttpContextAccessor httpContextAccessor = Substitute.For<IHttpContextAccessor>();
httpContextAccessor.HttpContext.Returns(_httpContext);
_sut = new PermissionAuthorizationHandler(_mockAuthorizationService, httpContextAccessor);
}
[Fact]
@@ -75,12 +85,50 @@ public class PermissionAuthorizationHandlerTests
Assert.False(context.HasSucceeded);
}
[Fact]
public async Task HandleAsync_WhenTheApiWasUnreachableDuringAnAuthenticatedPageNavigation_ShouldSucceed()
{
// Arrange
// The authorization service returns no role or permission when the API is unreachable, and marks the request instead.
_mockAuthorizationService.IsInRoleAsync(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(false);
_mockAuthorizationService.HasPermissionAsync(Arg.Any<AuthorizationPermission>(), Arg.Any<CancellationToken>()).Returns(false);
_httpContext.Items[HttpContextItemKeys.SERVER_UNREACHABLE] = true;
AuthorizationHandlerContext context = CreateContext();
// Act
await _sut.HandleAsync(context);
// Assert
Assert.True(context.HasSucceeded);
}
[Fact]
public async Task HandleAsync_WhenTheApiWasUnreachableDuringAnAnonymousPageNavigation_ShouldNotSucceed()
{
// Arrange
_mockAuthorizationService.IsInRoleAsync(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(false);
_mockAuthorizationService.HasPermissionAsync(Arg.Any<AuthorizationPermission>(), Arg.Any<CancellationToken>()).Returns(false);
_httpContext.User = new ClaimsPrincipal();
_httpContext.Items[HttpContextItemKeys.SERVER_UNREACHABLE] = true;
AuthorizationHandlerContext context = CreateContext();
// Act
await _sut.HandleAsync(context);
// Assert
Assert.False(context.HasSucceeded);
}
/// <summary>
/// Creates an authorization context that evaluates a requirement for the permission to manage media libraries.
/// </summary>
/// <returns>The created authorization context.</returns>
private static AuthorizationHandlerContext CreateContext()
{
return new AuthorizationHandlerContext([new PermissionRequirement(AuthorizationPermission.CanCreateLibraries)], new ClaimsPrincipal(), resource: null);
// Endpoint routing passes the endpoint, not the HttpContext, as the resource.
return new AuthorizationHandlerContext(
[new PermissionRequirement(AuthorizationPermission.CanCreateLibraries)],
new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString())], "TestAuthentication")),
new Endpoint(null, EndpointMetadataCollection.Empty, "test"));
}
}
@@ -0,0 +1,114 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Authorization;
using Lumina.Presentation.Web.Common.Http;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
using IAuthorizationService = Lumina.Presentation.Web.Common.Authorization.IAuthorizationService;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Common.Authorization;
/// <summary>
/// Contains unit tests for the <see cref="RoleAuthorizationHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RoleAuthorizationHandlerTests
{
private readonly IAuthorizationService _mockAuthorizationService;
private readonly DefaultHttpContext _httpContext;
private readonly RoleAuthorizationHandler _sut;
/// <summary>
/// Initializes a new instance of the <see cref="RoleAuthorizationHandlerTests"/> class.
/// </summary>
public RoleAuthorizationHandlerTests()
{
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_httpContext = new DefaultHttpContext
{
User = new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString())], "TestAuthentication"))
};
IHttpContextAccessor httpContextAccessor = Substitute.For<IHttpContextAccessor>();
httpContextAccessor.HttpContext.Returns(_httpContext);
_sut = new RoleAuthorizationHandler(_mockAuthorizationService, httpContextAccessor);
}
[Fact]
public async Task HandleAsync_WhenTheUserBelongsToTheRequiredRole_ShouldSucceed()
{
// Arrange
_mockAuthorizationService.IsInRoleAsync("Admin", Arg.Any<CancellationToken>()).Returns(true);
AuthorizationHandlerContext context = CreateContext();
// Act
await _sut.HandleAsync(context);
// Assert
Assert.True(context.HasSucceeded);
}
[Fact]
public async Task HandleAsync_WhenTheUserBelongsToNoneOfTheRequiredRoles_ShouldNotSucceed()
{
// Arrange
_mockAuthorizationService.IsInRoleAsync(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(false);
AuthorizationHandlerContext context = CreateContext();
// Act
await _sut.HandleAsync(context);
// Assert
Assert.False(context.HasSucceeded);
}
[Fact]
public async Task HandleAsync_WhenTheApiWasUnreachableDuringAnAuthenticatedPageNavigation_ShouldSucceed()
{
// Arrange
// The authorization service returns no role when the API is unreachable, and marks the request instead.
_mockAuthorizationService.IsInRoleAsync(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(false);
_httpContext.Items[HttpContextItemKeys.SERVER_UNREACHABLE] = true;
AuthorizationHandlerContext context = CreateContext();
// Act
await _sut.HandleAsync(context);
// Assert
Assert.True(context.HasSucceeded);
}
[Fact]
public async Task HandleAsync_WhenTheApiWasUnreachableDuringAnAnonymousPageNavigation_ShouldNotSucceed()
{
// Arrange
_mockAuthorizationService.IsInRoleAsync(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(false);
_httpContext.User = new ClaimsPrincipal();
_httpContext.Items[HttpContextItemKeys.SERVER_UNREACHABLE] = true;
AuthorizationHandlerContext context = CreateContext();
// Act
await _sut.HandleAsync(context);
// Assert
Assert.False(context.HasSucceeded);
}
/// <summary>
/// Creates an authorization context that evaluates a requirement for the administrator role.
/// </summary>
/// <returns>The created authorization context.</returns>
private static AuthorizationHandlerContext CreateContext()
{
// Endpoint routing passes the endpoint, not the HttpContext, as the resource.
return new AuthorizationHandlerContext(
[new RoleRequirement("Admin")],
new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString())], "TestAuthentication")),
new Endpoint(null, EndpointMetadataCollection.Empty, "test"));
}
}
@@ -66,10 +66,10 @@ public class ExceptionHandlingMiddlewareTests
}
[Fact]
public async Task InvokeAsync_WhenNextThrowsNonApiException_ShouldLogErrorAndWriteFailureJson()
public async Task InvokeAsync_WhenNextThrowsNonApiExceptionAndApiRequest_ShouldLogErrorAndWriteFailureJson()
{
// Arrange
DefaultHttpContext httpContext = CreateHttpContext();
DefaultHttpContext httpContext = CreateHttpContext(isApiRequest: true);
_nextDelegate = _ => throw new InvalidOperationException("Unexpected failure");
// Act
@@ -80,7 +80,8 @@ public class ExceptionHandlingMiddlewareTests
string body = await ReadResponseBodyAsync(httpContext);
using JsonDocument jsonDocument = JsonDocument.Parse(body);
Assert.False(jsonDocument.RootElement.GetProperty("success").GetBoolean());
Assert.Equal("Unexpected failure", jsonDocument.RootElement.GetProperty("errorMessage").GetString());
Assert.True(jsonDocument.RootElement.GetProperty("serverUnreachable").GetBoolean());
Assert.Equal("localized:InternalServerError", jsonDocument.RootElement.GetProperty("errorMessage").GetString());
_mockLogger.Received(1).Log(
LogLevel.Error,
Arg.Any<EventId>(),
@@ -89,6 +90,44 @@ public class ExceptionHandlingMiddlewareTests
Arg.Any<Func<object, Exception?, string>>());
}
[Fact]
public async Task InvokeAsync_WhenNextThrowsNonApiExceptionAndPageRequest_ShouldWriteHtmlErrorPage()
{
// Arrange
DefaultHttpContext httpContext = CreateHttpContext(culture: "de-DE");
_nextDelegate = _ => throw new InvalidOperationException("Unexpected failure");
// Act
await _sut.InvokeAsync(httpContext);
// Assert
Assert.Equal(StatusCodes.Status500InternalServerError, httpContext.Response.StatusCode);
Assert.Contains("text/html", httpContext.Response.ContentType);
Assert.Contains("localized:InternalServerError", await ReadResponseBodyAsync(httpContext));
_mockLogger.Received(1).Log(
LogLevel.Error,
Arg.Any<EventId>(),
Arg.Any<object>(),
Arg.Is<Exception>(exception => exception is InvalidOperationException && exception.Message == "Unexpected failure"),
Arg.Any<Func<object, Exception?, string>>());
}
[Fact]
public async Task InvokeAsync_WhenNextThrowsNonApiExceptionAndRawRequest_ShouldWriteStatusCodeWithoutBody()
{
// Arrange
DefaultHttpContext httpContext = CreateHttpContext();
httpContext.Request.Headers.Accept = "audio/mpeg";
_nextDelegate = _ => throw new InvalidOperationException("Unexpected failure");
// Act
await _sut.InvokeAsync(httpContext);
// Assert
Assert.Equal(StatusCodes.Status500InternalServerError, httpContext.Response.StatusCode);
Assert.Equal(0, httpContext.Response.Body.Length);
}
[Fact]
public async Task InvokeAsync_WhenApiExceptionUnauthorizedAndApiRequest_ShouldSignOutAndWriteUnauthorizedJson()
{
@@ -297,9 +336,45 @@ public class ExceptionHandlingMiddlewareTests
await _sut.InvokeAsync(httpContext);
// Assert
string errorMessage = await ReadErrorMessageAsync(httpContext);
string body = await ReadResponseBodyAsync(httpContext);
using JsonDocument jsonDocument = JsonDocument.Parse(body);
string errorMessage = jsonDocument.RootElement.GetProperty("errorMessage").GetString() ?? string.Empty;
Assert.Contains("An error occurred.", errorMessage);
Assert.Contains("localized:InternalServerError", errorMessage);
Assert.True(jsonDocument.RootElement.GetProperty("serverUnreachable").GetBoolean());
}
[Fact]
public async Task InvokeAsync_WhenApiExceptionHasNoProblemDetailsAndPageRequest_ShouldWriteHtmlErrorPage()
{
// Arrange
DefaultHttpContext httpContext = CreateHttpContext(culture: "en-US");
_nextDelegate = _ => throw new ApiException(null, HttpStatusCode.InternalServerError, "/api/v1/libraries/1");
// Act
await _sut.InvokeAsync(httpContext);
// Assert
Assert.Equal(StatusCodes.Status500InternalServerError, httpContext.Response.StatusCode);
Assert.Contains("text/html", httpContext.Response.ContentType);
Assert.Contains("localized:InternalServerError", await ReadResponseBodyAsync(httpContext));
}
[Fact]
public async Task InvokeAsync_WhenApiExceptionHasClientErrorAndPageRequest_ShouldWriteHtmlErrorPageWithTheRealStatusAndLocalizedMessage()
{
// Arrange
DefaultHttpContext httpContext = CreateHttpContext(culture: "en-US");
ProblemDetailsDto problemDetails = _problemDetailsDtoFixture.Create(detail: "Validation.Failed", title: "General.Validation", status: 422);
_nextDelegate = _ => throw new ApiException(problemDetails, (HttpStatusCode)422);
// Act
await _sut.InvokeAsync(httpContext);
// Assert
Assert.Equal(422, httpContext.Response.StatusCode);
Assert.Contains("text/html", httpContext.Response.ContentType);
Assert.Contains("localized:Validation.Failed", await ReadResponseBodyAsync(httpContext));
}
/// <summary>
@@ -44,6 +44,7 @@ public class ThemeLayoutRendererTests
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();
@@ -75,10 +76,12 @@ public class ThemeLayoutRendererTests
_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));
@@ -87,7 +90,7 @@ public class ThemeLayoutRendererTests
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);
_sut = new ThemeLayoutRenderer(themeService, new ThemeTemplateEngine(), viewRenderer, navBuilder, audioPlayerRenderer, _mockHttpContextAccessor, _mockStringLocalizerFactory);
}
[Fact]
@@ -188,6 +191,45 @@ public class ThemeLayoutRendererTests
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>