#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.DTO.Common;
using Lumina.Presentation.Web.Common.Exceptions;
using Lumina.Presentation.Web.Common.Middlewares;
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Net;
using System.Security.Claims;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Common.Middlewares;
///
/// Contains unit tests for the class.
///
[ExcludeFromCodeCoverage]
public class ExceptionHandlingMiddlewareTests
{
private readonly ILogger _mockLogger;
private readonly IStringLocalizer _mockStringLocalizer;
private readonly IAuthenticationService _mockAuthenticationService;
private readonly ExceptionHandlingMiddleware _sut;
private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new();
private RequestDelegate _nextDelegate;
///
/// Initializes a new instance of the class.
///
public ExceptionHandlingMiddlewareTests()
{
_mockLogger = Substitute.For>();
_mockStringLocalizer = Substitute.For>();
_mockStringLocalizer[Arg.Any()].Returns(callInfo => new LocalizedString(callInfo.Arg(), $"localized:{callInfo.Arg()}"));
_mockAuthenticationService = Substitute.For();
_mockAuthenticationService.SignOutAsync(Arg.Any(), Arg.Any(), Arg.Any()).Returns(Task.CompletedTask);
_mockAuthenticationService.ForbidAsync(Arg.Any(), Arg.Any(), Arg.Any()).Returns(Task.CompletedTask);
_nextDelegate = context => Task.CompletedTask;
_sut = new ExceptionHandlingMiddleware(context => _nextDelegate(context), _mockLogger, _mockStringLocalizer);
}
[Fact]
public async Task InvokeAsync_WhenNextCompletesSuccessfully_ShouldNotModifyResponse()
{
// Arrange
DefaultHttpContext httpContext = CreateHttpContext();
_nextDelegate = context => Task.CompletedTask;
// Act
await _sut.InvokeAsync(httpContext);
// Assert
Assert.Equal(StatusCodes.Status200OK, httpContext.Response.StatusCode);
Assert.Equal(0, httpContext.Response.Body.Length);
}
[Fact]
public async Task InvokeAsync_WhenNextThrowsNonApiExceptionAndApiRequest_ShouldLogErrorAndWriteFailureJson()
{
// Arrange
DefaultHttpContext httpContext = CreateHttpContext(isApiRequest: true);
_nextDelegate = _ => throw new InvalidOperationException("Unexpected failure");
// Act
await _sut.InvokeAsync(httpContext);
// Assert
Assert.Contains("application/json", httpContext.Response.ContentType);
string body = await ReadResponseBodyAsync(httpContext);
using JsonDocument jsonDocument = JsonDocument.Parse(body);
Assert.False(jsonDocument.RootElement.GetProperty("success").GetBoolean());
Assert.True(jsonDocument.RootElement.GetProperty("serverUnreachable").GetBoolean());
Assert.Equal("localized:InternalServerError", jsonDocument.RootElement.GetProperty("errorMessage").GetString());
_mockLogger.Received(1).Log(
LogLevel.Error,
Arg.Any(),
Arg.Any