mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 18:57:24 +00:00
Adds unit tests improving presentation web project code coverage
This commit is contained in:
1 parent
f3578f88d1
commit
759ef94050
6 files changed
+1470
No files matched your search
+116
@@ -0,0 +1,116 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Configuration;
|
||||
using Lumina.Presentation.Web.Common.HealthChecks;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Api;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Configuration;
|
||||
using Microsoft.Extensions.Diagnostics.HealthChecks;
|
||||
using Microsoft.Extensions.Options;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Common.HealthChecks;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ApiReachabilityHealthCheck"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ApiReachabilityHealthCheckTests
|
||||
{
|
||||
private readonly ServerConfigurationDtoFixture _serverConfigurationDtoFixture = new();
|
||||
|
||||
[Fact]
|
||||
public async Task CheckHealthAsync_WhenApiReturnsSuccess_ShouldReturnHealthyAndProbeReadyEndpoint()
|
||||
{
|
||||
// Arrange
|
||||
TestApiHttpMessageHandler messageHandler = new(_ => new HttpResponseMessage(HttpStatusCode.OK));
|
||||
ApiReachabilityHealthCheck sut = CreateSut(messageHandler);
|
||||
|
||||
// Act
|
||||
HealthCheckResult result = await sut.CheckHealthAsync(CreateHealthCheckContext(sut), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HealthStatus.Healthy, result.Status);
|
||||
Assert.Single(messageHandler.Requests);
|
||||
Assert.Equal("http://localhost:5214/health/ready", messageHandler.Requests[0].RequestUri!.ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CheckHealthAsync_WhenApiReturnsErrorStatus_ShouldReturnUnhealthyWithStatusCodeDescription()
|
||||
{
|
||||
// Arrange
|
||||
TestApiHttpMessageHandler messageHandler = new(_ => new HttpResponseMessage(HttpStatusCode.ServiceUnavailable));
|
||||
ApiReachabilityHealthCheck sut = CreateSut(messageHandler);
|
||||
|
||||
// Act
|
||||
HealthCheckResult result = await sut.CheckHealthAsync(CreateHealthCheckContext(sut), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HealthStatus.Unhealthy, result.Status);
|
||||
Assert.Equal("The API returned status 503.", result.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CheckHealthAsync_WhenApiRequestThrowsException_ShouldReturnUnhealthyWithException()
|
||||
{
|
||||
// Arrange
|
||||
TestApiHttpMessageHandler messageHandler = new(_ => throw new HttpRequestException("The API is down."));
|
||||
ApiReachabilityHealthCheck sut = CreateSut(messageHandler);
|
||||
|
||||
// Act
|
||||
HealthCheckResult result = await sut.CheckHealthAsync(CreateHealthCheckContext(sut), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HealthStatus.Unhealthy, result.Status);
|
||||
Assert.Equal("The API is not reachable.", result.Description);
|
||||
Assert.NotNull(result.Exception);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CheckHealthAsync_WhenCancellationIsRequestedBeforeProbe_ShouldReturnUnhealthy()
|
||||
{
|
||||
// Arrange
|
||||
TestApiHttpMessageHandler messageHandler = new(_ => new HttpResponseMessage(HttpStatusCode.OK));
|
||||
ApiReachabilityHealthCheck sut = CreateSut(messageHandler);
|
||||
CancellationTokenSource cancellationTokenSource = new();
|
||||
cancellationTokenSource.Cancel();
|
||||
|
||||
// Act
|
||||
HealthCheckResult result = await sut.CheckHealthAsync(CreateHealthCheckContext(sut), cancellationTokenSource.Token);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HealthStatus.Unhealthy, result.Status);
|
||||
Assert.Equal("The API is not reachable.", result.Description);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a <see cref="HealthCheckContext"/> whose registration points at the given health check.
|
||||
/// </summary>
|
||||
/// <param name="healthCheck">The health check to register in the context.</param>
|
||||
/// <returns>The created <see cref="HealthCheckContext"/> instance.</returns>
|
||||
private static HealthCheckContext CreateHealthCheckContext(IHealthCheck healthCheck)
|
||||
{
|
||||
// the ApiReachabilityHealthCheck never reads the registration, so a bare context is sufficient
|
||||
return new HealthCheckContext();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates the system under test configured with the provided message handler and a fixed server configuration.
|
||||
/// </summary>
|
||||
/// <param name="messageHandler">The message handler backing the inner <see cref="HttpClient"/>.</param>
|
||||
/// <returns>The created <see cref="ApiReachabilityHealthCheck"/>.</returns>
|
||||
private ApiReachabilityHealthCheck CreateSut(TestApiHttpMessageHandler messageHandler)
|
||||
{
|
||||
HttpClient httpClient = new(messageHandler);
|
||||
IHttpClientFactory httpClientFactory = Substitute.For<IHttpClientFactory>();
|
||||
httpClientFactory.CreateClient().Returns(httpClient);
|
||||
IOptionsSnapshot<ServerConfigurationDto> serverConfigurationOptions = Substitute.For<IOptionsSnapshot<ServerConfigurationDto>>();
|
||||
serverConfigurationOptions.Value.Returns(_serverConfigurationDtoFixture.Create(apiVersion: '1', baseAddress: "http://localhost", port: 5214));
|
||||
return new ApiReachabilityHealthCheck(httpClientFactory, serverConfigurationOptions);
|
||||
}
|
||||
}
|
||||
+397
@@ -0,0 +1,397 @@
|
||||
#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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ExceptionHandlingMiddleware"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ExceptionHandlingMiddlewareTests
|
||||
{
|
||||
private readonly ILogger<ExceptionHandlingMiddleware> _mockLogger;
|
||||
private readonly IStringLocalizer<ExceptionHandlingMiddleware> _mockStringLocalizer;
|
||||
private readonly IAuthenticationService _mockAuthenticationService;
|
||||
private readonly ExceptionHandlingMiddleware _sut;
|
||||
private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new();
|
||||
private RequestDelegate _nextDelegate;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ExceptionHandlingMiddlewareTests"/> class.
|
||||
/// </summary>
|
||||
public ExceptionHandlingMiddlewareTests()
|
||||
{
|
||||
_mockLogger = Substitute.For<ILogger<ExceptionHandlingMiddleware>>();
|
||||
_mockStringLocalizer = Substitute.For<IStringLocalizer<ExceptionHandlingMiddleware>>();
|
||||
_mockStringLocalizer[Arg.Any<string>()].Returns(callInfo => new LocalizedString(callInfo.Arg<string>(), $"localized:{callInfo.Arg<string>()}"));
|
||||
_mockAuthenticationService = Substitute.For<IAuthenticationService>();
|
||||
_mockAuthenticationService.SignOutAsync(Arg.Any<HttpContext>(), Arg.Any<string?>(), Arg.Any<AuthenticationProperties?>()).Returns(Task.CompletedTask);
|
||||
_mockAuthenticationService.ForbidAsync(Arg.Any<HttpContext>(), Arg.Any<string?>(), Arg.Any<AuthenticationProperties?>()).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_WhenNextThrowsNonApiException_ShouldLogErrorAndWriteFailureJson()
|
||||
{
|
||||
// Arrange
|
||||
DefaultHttpContext httpContext = CreateHttpContext();
|
||||
_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.Equal("Unexpected failure", jsonDocument.RootElement.GetProperty("errorMessage").GetString());
|
||||
_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_WhenApiExceptionUnauthorizedAndApiRequest_ShouldSignOutAndWriteUnauthorizedJson()
|
||||
{
|
||||
// Arrange
|
||||
DefaultHttpContext httpContext = CreateHttpContext(isApiRequest: true, requestServices: CreateServiceProvider());
|
||||
_nextDelegate = _ => throw new ApiException(null, HttpStatusCode.Unauthorized);
|
||||
|
||||
// Act
|
||||
await _sut.InvokeAsync(httpContext);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(StatusCodes.Status401Unauthorized, httpContext.Response.StatusCode);
|
||||
Assert.Equal("Unauthorized", await ReadErrorMessageAsync(httpContext));
|
||||
Assert.Contains("Token=", httpContext.Response.Headers["Set-Cookie"].ToString());
|
||||
await _mockAuthenticationService.Received(1).SignOutAsync(httpContext, CookieAuthenticationDefaults.AuthenticationScheme, Arg.Any<AuthenticationProperties?>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InvokeAsync_WhenApiExceptionUnauthorizedAndPageRequest_ShouldSignOutAndRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
DefaultHttpContext httpContext = CreateHttpContext(isApiRequest: false, culture: "en-US", requestServices: CreateServiceProvider());
|
||||
httpContext.Request.Path = "/library/books";
|
||||
httpContext.Request.QueryString = new QueryString("?id=1");
|
||||
_nextDelegate = _ => throw new ApiException(null, HttpStatusCode.Unauthorized);
|
||||
|
||||
// Act
|
||||
await _sut.InvokeAsync(httpContext);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(StatusCodes.Status302Found, httpContext.Response.StatusCode);
|
||||
Assert.Equal("/en-us/auth/login?returnUrl=%2Flibrary%2Fbooks%3Fid%3D1", httpContext.Response.Headers.Location.ToString());
|
||||
await _mockAuthenticationService.Received(1).SignOutAsync(httpContext, CookieAuthenticationDefaults.AuthenticationScheme, Arg.Any<AuthenticationProperties?>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InvokeAsync_WhenApiExceptionNotFoundAndApiRequest_ShouldWriteNotFoundJson()
|
||||
{
|
||||
// Arrange
|
||||
DefaultHttpContext httpContext = CreateHttpContext(isApiRequest: true);
|
||||
_nextDelegate = _ => throw new ApiException(_problemDetailsDtoFixture.Create(), HttpStatusCode.NotFound);
|
||||
|
||||
// Act
|
||||
await _sut.InvokeAsync(httpContext);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(StatusCodes.Status404NotFound, httpContext.Response.StatusCode);
|
||||
Assert.Equal("NotFound", await ReadErrorMessageAsync(httpContext));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InvokeAsync_WhenApiExceptionNotFoundAndPageRequest_ShouldRedirectToNotFoundPage()
|
||||
{
|
||||
// Arrange
|
||||
DefaultHttpContext httpContext = CreateHttpContext(isApiRequest: false, culture: "de-DE");
|
||||
_nextDelegate = _ => throw new ApiException(_problemDetailsDtoFixture.Create(), HttpStatusCode.NotFound);
|
||||
|
||||
// Act
|
||||
await _sut.InvokeAsync(httpContext);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(StatusCodes.Status302Found, httpContext.Response.StatusCode);
|
||||
Assert.Equal("/de-de/not-found", httpContext.Response.Headers.Location.ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InvokeAsync_WhenApiExceptionNotFoundForAuthenticatedAuthorizationCheckAndApiRequest_ShouldSignOutAndWriteUnauthorizedJson()
|
||||
{
|
||||
// Arrange
|
||||
DefaultHttpContext httpContext = CreateHttpContext(isApiRequest: true, user: CreateAuthenticatedUser(), requestServices: CreateServiceProvider());
|
||||
_nextDelegate = _ => throw new ApiException(_problemDetailsDtoFixture.Create(), HttpStatusCode.NotFound, "/api/v1/auth/get-authorization?userId=1");
|
||||
|
||||
// Act
|
||||
await _sut.InvokeAsync(httpContext);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(StatusCodes.Status401Unauthorized, httpContext.Response.StatusCode);
|
||||
Assert.Equal("Unauthorized", await ReadErrorMessageAsync(httpContext));
|
||||
await _mockAuthenticationService.Received(1).SignOutAsync(httpContext, CookieAuthenticationDefaults.AuthenticationScheme, Arg.Any<AuthenticationProperties?>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InvokeAsync_WhenApiExceptionNotFoundForAuthenticatedAuthorizationCheckAndPageRequest_ShouldSignOutAndRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
DefaultHttpContext httpContext = CreateHttpContext(isApiRequest: false, culture: null, user: CreateAuthenticatedUser(), requestServices: CreateServiceProvider());
|
||||
httpContext.Request.Path = "/dashboard";
|
||||
_nextDelegate = _ => throw new ApiException(_problemDetailsDtoFixture.Create(), HttpStatusCode.NotFound, "/api/v1/auth/get-authorization?userId=1");
|
||||
|
||||
// Act
|
||||
await _sut.InvokeAsync(httpContext);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(StatusCodes.Status302Found, httpContext.Response.StatusCode);
|
||||
Assert.Equal("/en-us/auth/login?returnUrl=%2Fdashboard", httpContext.Response.Headers.Location.ToString());
|
||||
await _mockAuthenticationService.Received(1).SignOutAsync(httpContext, CookieAuthenticationDefaults.AuthenticationScheme, Arg.Any<AuthenticationProperties?>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InvokeAsync_WhenApiExceptionForbiddenAndApiRequest_ShouldWriteFailureJsonWithProblemDetail()
|
||||
{
|
||||
// Arrange
|
||||
DefaultHttpContext httpContext = CreateHttpContext(isApiRequest: true);
|
||||
ProblemDetailsDto problemDetails = _problemDetailsDtoFixture.Create(detail: "Access.Denied", title: "General.Forbidden");
|
||||
_nextDelegate = _ => throw new ApiException(problemDetails, HttpStatusCode.Forbidden);
|
||||
|
||||
// Act
|
||||
await _sut.InvokeAsync(httpContext);
|
||||
|
||||
// Assert
|
||||
string errorMessage = await ReadErrorMessageAsync(httpContext);
|
||||
Assert.Contains("localized:Access.Denied", errorMessage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InvokeAsync_WhenApiExceptionForbiddenAndPageRequest_ShouldForbidTheRequest()
|
||||
{
|
||||
// Arrange
|
||||
DefaultHttpContext httpContext = CreateHttpContext(isApiRequest: false, requestServices: CreateServiceProvider());
|
||||
_nextDelegate = _ => throw new ApiException(_problemDetailsDtoFixture.Create(), HttpStatusCode.Forbidden);
|
||||
|
||||
// Act
|
||||
await _sut.InvokeAsync(httpContext);
|
||||
|
||||
// Assert
|
||||
await _mockAuthenticationService.Received(1).ForbidAsync(httpContext, Arg.Any<string?>(), Arg.Any<AuthenticationProperties?>());
|
||||
Assert.Equal(0, httpContext.Response.Body.Length);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InvokeAsync_WhenApiExceptionForbiddenAndXmlHttpRequestHeader_ShouldWriteFailureJson()
|
||||
{
|
||||
// Arrange
|
||||
DefaultHttpContext httpContext = CreateHttpContext(isApiRequest: false);
|
||||
httpContext.Request.Headers.XRequestedWith = "XMLHttpRequest";
|
||||
ProblemDetailsDto problemDetails = _problemDetailsDtoFixture.Create(detail: "Access.Denied", title: "General.Forbidden");
|
||||
_nextDelegate = _ => throw new ApiException(problemDetails, HttpStatusCode.Forbidden);
|
||||
|
||||
// Act
|
||||
await _sut.InvokeAsync(httpContext);
|
||||
|
||||
// Assert
|
||||
string errorMessage = await ReadErrorMessageAsync(httpContext);
|
||||
Assert.Contains("localized:Access.Denied", errorMessage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InvokeAsync_WhenApiExceptionHasProblemDetail_ShouldWriteLocalizedDetailMessage()
|
||||
{
|
||||
// Arrange
|
||||
DefaultHttpContext httpContext = CreateHttpContext(isApiRequest: true);
|
||||
ProblemDetailsDto problemDetails = _problemDetailsDtoFixture.Create(detail: "Validation.Failed", title: "General.Validation", status: 400);
|
||||
_nextDelegate = _ => throw new ApiException(problemDetails, HttpStatusCode.BadRequest);
|
||||
|
||||
// Act
|
||||
await _sut.InvokeAsync(httpContext);
|
||||
|
||||
// Assert
|
||||
string errorMessage = await ReadErrorMessageAsync(httpContext);
|
||||
Assert.Contains("localized:Validation.Failed", errorMessage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InvokeAsync_WhenApiExceptionHasOnlyProblemTitle_ShouldWriteLocalizedTitleMessage()
|
||||
{
|
||||
// Arrange
|
||||
DefaultHttpContext httpContext = CreateHttpContext(isApiRequest: true);
|
||||
ProblemDetailsDto problemDetails = new()
|
||||
{
|
||||
Title = "General.Failure",
|
||||
Status = 400
|
||||
};
|
||||
_nextDelegate = _ => throw new ApiException(problemDetails, HttpStatusCode.BadRequest);
|
||||
|
||||
// Act
|
||||
await _sut.InvokeAsync(httpContext);
|
||||
|
||||
// Assert
|
||||
string errorMessage = await ReadErrorMessageAsync(httpContext);
|
||||
Assert.Contains("localized:General.Failure", errorMessage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InvokeAsync_WhenApiExceptionProblemDetailsContainValidationErrors_ShouldWriteLocalizedFieldErrors()
|
||||
{
|
||||
// Arrange
|
||||
DefaultHttpContext httpContext = CreateHttpContext(isApiRequest: true);
|
||||
ProblemDetailsDto problemDetails = DeserializeProblemDetailsWithErrors();
|
||||
_nextDelegate = _ => throw new ApiException(problemDetails, HttpStatusCode.BadRequest);
|
||||
|
||||
// Act
|
||||
await _sut.InvokeAsync(httpContext);
|
||||
|
||||
// Assert
|
||||
string errorMessage = await ReadErrorMessageAsync(httpContext);
|
||||
Assert.Contains("localized:General.Validation", errorMessage);
|
||||
Assert.Contains("localized:EmailIsInvalid", errorMessage);
|
||||
Assert.Contains("localized:EmailIsTaken", errorMessage);
|
||||
Assert.Contains("localized:PasswordTooShort", errorMessage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InvokeAsync_WhenApiExceptionHasNoProblemDetails_ShouldWriteExceptionMessageAndLocalizedStatus()
|
||||
{
|
||||
// Arrange
|
||||
DefaultHttpContext httpContext = CreateHttpContext(isApiRequest: true);
|
||||
_nextDelegate = _ => throw new ApiException(null, HttpStatusCode.InternalServerError, "/api/v1/libraries/1");
|
||||
|
||||
// Act
|
||||
await _sut.InvokeAsync(httpContext);
|
||||
|
||||
// Assert
|
||||
string errorMessage = await ReadErrorMessageAsync(httpContext);
|
||||
Assert.Contains("An error occurred.", errorMessage);
|
||||
Assert.Contains("localized:InternalServerError", errorMessage);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a <see cref="DefaultHttpContext"/> with a writable response body and optional API/user/culture/service configuration.
|
||||
/// </summary>
|
||||
/// <param name="isApiRequest">Whether the request accepts JSON, making it an API request.</param>
|
||||
/// <param name="culture">The culture route value, <see langword="null"/> when no route value is present.</param>
|
||||
/// <param name="user">The user associated with the context, <see langword="null"/> for anonymous requests.</param>
|
||||
/// <param name="requestServices">The request services, <see langword="null"/> to leave the default provider in place.</param>
|
||||
/// <returns>The configured <see cref="DefaultHttpContext"/> instance.</returns>
|
||||
private static DefaultHttpContext CreateHttpContext(bool isApiRequest = false, string? culture = null, ClaimsPrincipal? user = null, IServiceProvider? requestServices = null)
|
||||
{
|
||||
DefaultHttpContext httpContext = new()
|
||||
{
|
||||
Response = { Body = new MemoryStream() }
|
||||
};
|
||||
if (isApiRequest)
|
||||
httpContext.Request.Headers.Accept = "application/json";
|
||||
if (culture is not null)
|
||||
httpContext.Request.RouteValues["culture"] = culture;
|
||||
if (user is not null)
|
||||
httpContext.User = user;
|
||||
if (requestServices is not null)
|
||||
httpContext.RequestServices = requestServices;
|
||||
return httpContext;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a service provider that resolves the mocked <see cref="IAuthenticationService"/>.
|
||||
/// </summary>
|
||||
/// <returns>The configured <see cref="IServiceProvider"/> instance.</returns>
|
||||
private IServiceProvider CreateServiceProvider()
|
||||
{
|
||||
ServiceCollection services = new();
|
||||
services.AddSingleton(_mockAuthenticationService);
|
||||
return services.BuildServiceProvider();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an authenticated user principal with a name identifier claim.
|
||||
/// </summary>
|
||||
/// <returns>The created <see cref="ClaimsPrincipal"/> instance.</returns>
|
||||
private static ClaimsPrincipal CreateAuthenticatedUser()
|
||||
{
|
||||
return new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString())], "TestAuthentication"));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the current response body of the provided HTTP context.
|
||||
/// </summary>
|
||||
/// <param name="httpContext">The HTTP context whose response body is read.</param>
|
||||
/// <returns>The response body content.</returns>
|
||||
private static async Task<string> ReadResponseBodyAsync(HttpContext httpContext)
|
||||
{
|
||||
httpContext.Response.Body.Position = 0;
|
||||
using StreamReader reader = new(httpContext.Response.Body, Encoding.UTF8);
|
||||
return await reader.ReadToEndAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the <c>errorMessage</c> property from the JSON response body of the provided HTTP context.
|
||||
/// </summary>
|
||||
/// <param name="httpContext">The HTTP context whose JSON response body is read.</param>
|
||||
/// <returns>The value of the <c>errorMessage</c> property.</returns>
|
||||
private static async Task<string> ReadErrorMessageAsync(HttpContext httpContext)
|
||||
{
|
||||
string body = await ReadResponseBodyAsync(httpContext);
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
return jsonDocument.RootElement.GetProperty("errorMessage").GetString() ?? string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserializes a problem details payload that contains a validation errors extension object.
|
||||
/// </summary>
|
||||
/// <returns>The deserialized <see cref="ProblemDetailsDto"/> instance.</returns>
|
||||
private static ProblemDetailsDto DeserializeProblemDetailsWithErrors()
|
||||
{
|
||||
string problemDetailsJson = """
|
||||
{
|
||||
"type": "https://tools.ietf.org/html/rfc4918#section-11.2",
|
||||
"title": "General.Validation",
|
||||
"status": 400,
|
||||
"errors": {
|
||||
"Email": ["EmailIsInvalid", "EmailIsTaken"],
|
||||
"Password": ["PasswordTooShort"]
|
||||
}
|
||||
}
|
||||
""";
|
||||
return JsonSerializer.Deserialize<ProblemDetailsDto>(problemDetailsJson)!;
|
||||
}
|
||||
}
|
||||
+224
@@ -0,0 +1,224 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Middlewares;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.Features;
|
||||
using Microsoft.AspNetCore.Localization;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Common.Middlewares;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="NotFoundRedirectMiddleware"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class NotFoundRedirectMiddlewareTests
|
||||
{
|
||||
private readonly ILogger<NotFoundRedirectMiddleware> _mockLogger;
|
||||
private readonly NotFoundRedirectMiddleware _sut;
|
||||
private RequestDelegate _nextDelegate;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="NotFoundRedirectMiddlewareTests"/> class.
|
||||
/// </summary>
|
||||
public NotFoundRedirectMiddlewareTests()
|
||||
{
|
||||
_mockLogger = Substitute.For<ILogger<NotFoundRedirectMiddleware>>();
|
||||
_nextDelegate = context => Task.CompletedTask;
|
||||
_sut = new NotFoundRedirectMiddleware(context => _nextDelegate(context), _mockLogger);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InvokeAsync_WhenResponseIs404AndResponseHasNotStarted_ShouldReexecuteRequestAgainstNotFoundPage()
|
||||
{
|
||||
// Arrange
|
||||
int invocationCount = 0;
|
||||
string? invokedPath = null;
|
||||
_nextDelegate = context =>
|
||||
{
|
||||
invocationCount++;
|
||||
invokedPath = context.Request.Path.Value;
|
||||
if (invocationCount == 1)
|
||||
context.Response.StatusCode = StatusCodes.Status404NotFound;
|
||||
return Task.CompletedTask;
|
||||
};
|
||||
DefaultHttpContext httpContext = CreateHttpContext(culture: "de-DE");
|
||||
httpContext.Request.Path = "/en-us/books/123";
|
||||
|
||||
// Act
|
||||
await _sut.InvokeAsync(httpContext);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(2, invocationCount);
|
||||
Assert.Equal("/de-de/not-found", invokedPath);
|
||||
Assert.Equal("/de-de/not-found", httpContext.Request.Path.Value);
|
||||
Assert.Equal("/en-us/books/123", httpContext.Items["originalPath"] as string);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, httpContext.Response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InvokeAsync_WhenCultureComesFromRequestCultureFeature_ShouldUseTheFeatureCulture()
|
||||
{
|
||||
// Arrange
|
||||
int invocationCount = 0;
|
||||
string? invokedPath = null;
|
||||
_nextDelegate = context =>
|
||||
{
|
||||
invocationCount++;
|
||||
invokedPath = context.Request.Path.Value;
|
||||
if (invocationCount == 1)
|
||||
context.Response.StatusCode = StatusCodes.Status404NotFound;
|
||||
return Task.CompletedTask;
|
||||
};
|
||||
DefaultHttpContext httpContext = CreateHttpContext(culture: null);
|
||||
IRequestCultureFeature requestCultureFeature = Substitute.For<IRequestCultureFeature>();
|
||||
requestCultureFeature.RequestCulture.Returns(new RequestCulture("fr-FR"));
|
||||
httpContext.Features.Set<IRequestCultureFeature>(requestCultureFeature);
|
||||
|
||||
// Act
|
||||
await _sut.InvokeAsync(httpContext);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(2, invocationCount);
|
||||
Assert.Equal("/fr-fr/not-found", invokedPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InvokeAsync_WhenNoCultureSourceIsAvailable_ShouldFallBackToDefaultCulture()
|
||||
{
|
||||
// Arrange
|
||||
int invocationCount = 0;
|
||||
string? invokedPath = null;
|
||||
_nextDelegate = context =>
|
||||
{
|
||||
invocationCount++;
|
||||
invokedPath = context.Request.Path.Value;
|
||||
if (invocationCount == 1)
|
||||
context.Response.StatusCode = StatusCodes.Status404NotFound;
|
||||
return Task.CompletedTask;
|
||||
};
|
||||
DefaultHttpContext httpContext = CreateHttpContext(culture: null);
|
||||
|
||||
// Act
|
||||
await _sut.InvokeAsync(httpContext);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(2, invocationCount);
|
||||
Assert.Equal("/en-us/not-found", invokedPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InvokeAsync_WhenResponseStatusIsNot404_ShouldNotReexecuteRequest()
|
||||
{
|
||||
// Arrange
|
||||
int invocationCount = 0;
|
||||
_nextDelegate = context =>
|
||||
{
|
||||
invocationCount++;
|
||||
context.Response.StatusCode = StatusCodes.Status200OK;
|
||||
return Task.CompletedTask;
|
||||
};
|
||||
DefaultHttpContext httpContext = CreateHttpContext(culture: "de-DE");
|
||||
httpContext.Request.Path = "/en-us/books/123";
|
||||
|
||||
// Act
|
||||
await _sut.InvokeAsync(httpContext);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(1, invocationCount);
|
||||
Assert.Equal("/en-us/books/123", httpContext.Request.Path.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InvokeAsync_WhenResponseIs404AndResponseHasStarted_ShouldNotReexecuteRequest()
|
||||
{
|
||||
// Arrange
|
||||
int invocationCount = 0;
|
||||
_nextDelegate = context =>
|
||||
{
|
||||
invocationCount++;
|
||||
context.Response.StatusCode = StatusCodes.Status404NotFound;
|
||||
return Task.CompletedTask;
|
||||
};
|
||||
DefaultHttpContext httpContext = CreateHttpContext(culture: "de-DE");
|
||||
httpContext.Request.Path = "/en-us/books/123";
|
||||
httpContext.Features.Set<IHttpResponseFeature>(new StartedHttpResponseFeature());
|
||||
|
||||
// Act
|
||||
await _sut.InvokeAsync(httpContext);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(1, invocationCount);
|
||||
Assert.Equal("/en-us/books/123", httpContext.Request.Path.Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a <see cref="DefaultHttpContext"/> with a writable response body and an optional culture route value.
|
||||
/// </summary>
|
||||
/// <param name="culture">The culture route value, <see langword="null"/> when no route value is present.</param>
|
||||
/// <returns>The configured <see cref="DefaultHttpContext"/> instance.</returns>
|
||||
private static DefaultHttpContext CreateHttpContext(string? culture)
|
||||
{
|
||||
DefaultHttpContext httpContext = new()
|
||||
{
|
||||
Response = { Body = new MemoryStream() }
|
||||
};
|
||||
if (culture is not null)
|
||||
httpContext.Request.RouteValues["culture"] = culture;
|
||||
return httpContext;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Response feature that reports the response as already started, for simulating a response that cannot be replaced.
|
||||
/// </summary>
|
||||
private sealed class StartedHttpResponseFeature : IHttpResponseFeature
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the HTTP status code of the response.
|
||||
/// </summary>
|
||||
public int StatusCode { get; set; } = StatusCodes.Status200OK;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the reason phrase of the response.
|
||||
/// </summary>
|
||||
public string? ReasonPhrase { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the response headers.
|
||||
/// </summary>
|
||||
public IHeaderDictionary Headers { get; set; } = new HeaderDictionary();
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the response body stream.
|
||||
/// </summary>
|
||||
public Stream Body { get; set; } = Stream.Null;
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the response has already started.
|
||||
/// </summary>
|
||||
public bool HasStarted => true;
|
||||
|
||||
/// <summary>
|
||||
/// Registers a callback to be invoked when the response is about to start.
|
||||
/// </summary>
|
||||
/// <param name="callback">The callback to invoke.</param>
|
||||
/// <param name="state">The state passed to the callback.</param>
|
||||
public void OnStarting(Func<object, Task> callback, object state)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers a callback to be invoked when the response has completed.
|
||||
/// </summary>
|
||||
/// <param name="callback">The callback to invoke.</param>
|
||||
/// <param name="state">The state passed to the callback.</param>
|
||||
public void OnCompleted(Func<object, Task> callback, object state)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
+192
@@ -0,0 +1,192 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Services;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Api;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Caching.Hybrid;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Common.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="CachedAuthorizationHandler"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class CachedAuthorizationHandlerTests
|
||||
{
|
||||
private const string AUTHORIZATION_ENDPOINT = "http://localhost:5214/api/v1/auth/get-authorization";
|
||||
private const string LOGIN_ENDPOINT = "http://localhost:5214/api/v1/auth/login";
|
||||
private readonly HybridCache _hybridCache;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CachedAuthorizationHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public CachedAuthorizationHandlerTests()
|
||||
{
|
||||
ServiceCollection services = new();
|
||||
services.AddHybridCache();
|
||||
_hybridCache = services.BuildServiceProvider().GetRequiredService<HybridCache>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendAsync_WhenAuthorizationRequestIsServedTwice_ShouldCallInnerHandlerOnlyOnce()
|
||||
{
|
||||
// Arrange
|
||||
TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.OK, """{"role":"Admin","permissions":[]}"""));
|
||||
HttpClient client = CreateClient(userId: Guid.NewGuid(), messageHandler);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage firstResponse = await client.GetAsync(AUTHORIZATION_ENDPOINT, CancellationToken.None);
|
||||
HttpResponseMessage secondResponse = await client.GetAsync(AUTHORIZATION_ENDPOINT, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Single(messageHandler.Requests);
|
||||
Assert.Equal(HttpStatusCode.OK, firstResponse.StatusCode);
|
||||
Assert.Equal(HttpStatusCode.OK, secondResponse.StatusCode);
|
||||
Assert.Equal(await firstResponse.Content.ReadAsStringAsync(), await secondResponse.Content.ReadAsStringAsync());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendAsync_WhenNonAuthorizationRequestIsServedTwice_ShouldCallInnerHandlerTwice()
|
||||
{
|
||||
// Arrange
|
||||
TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.OK, """[{"title":"Library One"}]"""));
|
||||
HttpClient client = CreateClient(userId: Guid.NewGuid(), messageHandler);
|
||||
|
||||
// Act
|
||||
await client.GetAsync("http://localhost:5214/api/v1/libraries", CancellationToken.None);
|
||||
await client.GetAsync("http://localhost:5214/api/v1/libraries", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(2, messageHandler.Requests.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendAsync_WhenLoginRequestFollowsCachedAuthorizationRequest_ShouldInvalidateCachedAuthorization()
|
||||
{
|
||||
// Arrange
|
||||
TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.OK, """{"role":"Admin","permissions":[]}"""));
|
||||
HttpClient client = CreateClient(userId: Guid.NewGuid(), messageHandler);
|
||||
|
||||
// Act
|
||||
await client.GetAsync(AUTHORIZATION_ENDPOINT, CancellationToken.None);
|
||||
await client.PostAsync(LOGIN_ENDPOINT, new StringContent("""{"username":"testuser","password":"TestPass123!"}""", Encoding.UTF8, "application/json"), CancellationToken.None);
|
||||
await client.GetAsync(AUTHORIZATION_ENDPOINT, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(3, messageHandler.Requests.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendAsync_WhenAuthorizationReturnsUnauthorized_ShouldNotRetainTheCachedResponse()
|
||||
{
|
||||
// Arrange
|
||||
TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.Unauthorized, """{"title":"Unauthorized"}"""));
|
||||
HttpClient client = CreateClient(userId: Guid.NewGuid(), messageHandler);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage firstResponse = await client.GetAsync(AUTHORIZATION_ENDPOINT, CancellationToken.None);
|
||||
HttpResponseMessage secondResponse = await client.GetAsync(AUTHORIZATION_ENDPOINT, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(2, messageHandler.Requests.Count);
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, firstResponse.StatusCode);
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, secondResponse.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendAsync_WhenAuthorizationReturnsNotFound_ShouldNotRetainTheCachedResponse()
|
||||
{
|
||||
// Arrange
|
||||
TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.NotFound, """{"title":"NotFound"}"""));
|
||||
HttpClient client = CreateClient(userId: Guid.NewGuid(), messageHandler);
|
||||
|
||||
// Act
|
||||
await client.GetAsync(AUTHORIZATION_ENDPOINT, CancellationToken.None);
|
||||
await client.GetAsync(AUTHORIZATION_ENDPOINT, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(2, messageHandler.Requests.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendAsync_WhenAuthorizationRequestIsMadeWithoutAuthenticatedUser_ShouldStillCacheTheResponse()
|
||||
{
|
||||
// Arrange
|
||||
TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.OK, """{"role":"Admin","permissions":[]}"""));
|
||||
HttpClient client = CreateClient(userId: null, messageHandler);
|
||||
|
||||
// Act
|
||||
await client.GetAsync(AUTHORIZATION_ENDPOINT, CancellationToken.None);
|
||||
await client.GetAsync(AUTHORIZATION_ENDPOINT, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Single(messageHandler.Requests);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendAsync_WhenDifferentUsersRequestAuthorization_ShouldServeSeparateCachedResponses()
|
||||
{
|
||||
// Arrange
|
||||
TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.OK, """{"role":"Admin","permissions":[]}"""));
|
||||
HttpClient firstClient = CreateClient(userId: Guid.NewGuid(), messageHandler);
|
||||
HttpClient secondClient = CreateClient(userId: Guid.NewGuid(), messageHandler);
|
||||
|
||||
// Act
|
||||
await firstClient.GetAsync(AUTHORIZATION_ENDPOINT, CancellationToken.None);
|
||||
await firstClient.GetAsync(AUTHORIZATION_ENDPOINT, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(1, messageHandler.Requests.Count);
|
||||
|
||||
// Act
|
||||
await secondClient.GetAsync(AUTHORIZATION_ENDPOINT, CancellationToken.None);
|
||||
await secondClient.GetAsync(AUTHORIZATION_ENDPOINT, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(2, messageHandler.Requests.Count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an <see cref="HttpClient"/> that pipes requests through a <see cref="CachedAuthorizationHandler"/> backed by the given inner handler.
|
||||
/// </summary>
|
||||
/// <param name="userId">The user id claim placed on the current HTTP context user, <see langword="null"/> for anonymous requests.</param>
|
||||
/// <param name="messageHandler">The message handler backing the inner <see cref="HttpClient"/> pipeline.</param>
|
||||
/// <returns>The created <see cref="HttpClient"/>.</returns>
|
||||
private HttpClient CreateClient(Guid? userId, TestApiHttpMessageHandler messageHandler)
|
||||
{
|
||||
IHttpContextAccessor httpContextAccessor = Substitute.For<IHttpContextAccessor>();
|
||||
DefaultHttpContext httpContext = new();
|
||||
if (userId is not null)
|
||||
httpContext.User = new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, userId.Value.ToString())], "TestAuthentication"));
|
||||
httpContextAccessor.HttpContext.Returns(httpContext);
|
||||
CachedAuthorizationHandler authorizationHandler = new(_hybridCache, httpContextAccessor)
|
||||
{
|
||||
InnerHandler = messageHandler
|
||||
};
|
||||
return new HttpClient(authorizationHandler);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an <see cref="HttpResponseMessage"/> with the given status code and JSON body.
|
||||
/// </summary>
|
||||
/// <param name="statusCode">The HTTP status code of the response.</param>
|
||||
/// <param name="json">The JSON payload of the response body.</param>
|
||||
/// <returns>The created <see cref="HttpResponseMessage"/>.</returns>
|
||||
private static HttpResponseMessage CreateJsonResponse(HttpStatusCode statusCode, string json)
|
||||
{
|
||||
return new HttpResponseMessage(statusCode)
|
||||
{
|
||||
Content = new StringContent(json, Encoding.UTF8, "application/json")
|
||||
};
|
||||
}
|
||||
}
|
||||
+148
@@ -0,0 +1,148 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Primitives;
|
||||
using Lumina.Presentation.Web.Common.Validation;
|
||||
using Microsoft.Extensions.Options;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Common.Validation;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ValidationOptions{TOptions}"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ValidationOptionsTests
|
||||
{
|
||||
[Fact]
|
||||
public void Validate_WhenMatchingName_ShouldValidateOptions()
|
||||
{
|
||||
// Arrange
|
||||
string optionsName = "OptionsName";
|
||||
TestOptions options = new();
|
||||
IValidator<TestOptions> validator = Substitute.For<IValidator<TestOptions>>();
|
||||
validator.Validate(options).Returns([]);
|
||||
ValidationOptions<TestOptions> sut = new(optionsName, validator);
|
||||
|
||||
// Act
|
||||
ValidateOptionsResult result = sut.Validate(optionsName, options);
|
||||
|
||||
// Assert
|
||||
Assert.IsType<ValidateOptionsResult>(result);
|
||||
Assert.False(result.Failed);
|
||||
validator.Received(1).Validate(options);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenNonMatchingName_ShouldSkipValidation()
|
||||
{
|
||||
// Arrange
|
||||
string optionsName = "OptionsName";
|
||||
string differentOptionsName = "DifferentOptionsName";
|
||||
TestOptions options = new();
|
||||
IValidator<TestOptions> validator = Substitute.For<IValidator<TestOptions>>();
|
||||
ValidationOptions<TestOptions> sut = new(optionsName, validator);
|
||||
|
||||
// Act
|
||||
ValidateOptionsResult result = sut.Validate(differentOptionsName, options);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(ValidateOptionsResult.Skip, result);
|
||||
validator.DidNotReceive().Validate(options);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenNullName_ShouldValidateOptions()
|
||||
{
|
||||
// Arrange
|
||||
TestOptions options = new();
|
||||
IValidator<TestOptions> validator = Substitute.For<IValidator<TestOptions>>();
|
||||
validator.Validate(options).Returns([]);
|
||||
ValidationOptions<TestOptions> sut = new(null, validator);
|
||||
|
||||
// Act
|
||||
ValidateOptionsResult result = sut.Validate("AnyOptionsName", options);
|
||||
|
||||
// Assert
|
||||
Assert.IsType<ValidateOptionsResult>(result);
|
||||
Assert.False(result.Failed);
|
||||
validator.Received(1).Validate(options);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenNullOptions_ShouldThrowArgumentNullException()
|
||||
{
|
||||
// Arrange
|
||||
string optionsName = "OptionsName";
|
||||
IValidator<TestOptions> validator = Substitute.For<IValidator<TestOptions>>();
|
||||
ValidationOptions<TestOptions> sut = new(optionsName, validator);
|
||||
|
||||
// Act
|
||||
Action act = () => sut.Validate(optionsName, null!);
|
||||
|
||||
// Assert
|
||||
Assert.Throws<ArgumentNullException>(act);
|
||||
validator.DidNotReceive().Validate(Arg.Any<TestOptions>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenInvalidOptions_ShouldReturnFailureResult()
|
||||
{
|
||||
// Arrange
|
||||
string optionsName = "OptionsName";
|
||||
TestOptions options = new();
|
||||
IValidator<TestOptions> validator = Substitute.For<IValidator<TestOptions>>();
|
||||
List<Error> validationFailures =
|
||||
[
|
||||
Error.Validation("PropertyName", "Error Message")
|
||||
];
|
||||
validator.Validate(options).Returns(validationFailures);
|
||||
ValidationOptions<TestOptions> sut = new(optionsName, validator);
|
||||
|
||||
// Act
|
||||
ValidateOptionsResult result = sut.Validate(optionsName, options);
|
||||
|
||||
// Assert
|
||||
Assert.IsType<ValidateOptionsResult>(result);
|
||||
Assert.True(result.Failed);
|
||||
Assert.Single(result.Failures);
|
||||
Assert.Contains("Options validation failed for 'PropertyName' with error: 'Error Message'", result.Failures);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenMultipleValidationErrors_ShouldReturnOneFailureMessagePerError()
|
||||
{
|
||||
// Arrange
|
||||
string optionsName = "OptionsName";
|
||||
TestOptions options = new();
|
||||
IValidator<TestOptions> validator = Substitute.For<IValidator<TestOptions>>();
|
||||
List<Error> validationFailures =
|
||||
[
|
||||
Error.Validation("PropertyOne", "First Error Message"),
|
||||
Error.Validation("PropertyTwo", "Second Error Message")
|
||||
];
|
||||
validator.Validate(options).Returns(validationFailures);
|
||||
ValidationOptions<TestOptions> sut = new(optionsName, validator);
|
||||
|
||||
// Act
|
||||
ValidateOptionsResult result = sut.Validate(optionsName, options);
|
||||
|
||||
// Assert
|
||||
Assert.IsType<ValidateOptionsResult>(result);
|
||||
Assert.True(result.Failed);
|
||||
Assert.Equal(2, result.Failures.Count());
|
||||
Assert.Contains("Options validation failed for 'PropertyOne' with error: 'First Error Message'", result.Failures);
|
||||
Assert.Contains("Options validation failed for 'PropertyTwo' with error: 'Second Error Message'", result.Failures);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Placeholder options type used to exercise the generic <see cref="ValidationOptions{TOptions}"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public sealed class TestOptions
|
||||
{
|
||||
}
|
||||
}
|
||||
+393
@@ -0,0 +1,393 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Primitives;
|
||||
using Lumina.Presentation.Web.Common.Validation;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Common.Validation;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ValidationRuleForEach{TRequest, TItem}"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ValidationRuleForEachTests
|
||||
{
|
||||
private readonly ValidationRuleForEach<TestRequest, string> _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ValidationRuleForEachTests"/> class.
|
||||
/// </summary>
|
||||
public ValidationRuleForEachTests()
|
||||
{
|
||||
_sut = new ValidationRuleForEach<TestRequest, string>(request => request.Items);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenNoPredicatesConfigured_ShouldReturnNoErrors()
|
||||
{
|
||||
// Arrange
|
||||
TestRequest request = new()
|
||||
{
|
||||
Items = ["value"]
|
||||
};
|
||||
|
||||
// Act
|
||||
List<Error> result = [.. _sut.Validate(request)];
|
||||
|
||||
// Assert
|
||||
Assert.Empty(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenCollectionIsNull_ShouldReturnNoErrors()
|
||||
{
|
||||
// Arrange
|
||||
_sut.Must(item => item.Length > 0);
|
||||
TestRequest request = new()
|
||||
{
|
||||
Items = null
|
||||
};
|
||||
|
||||
// Act
|
||||
List<Error> result = [.. _sut.Validate(request)];
|
||||
|
||||
// Assert
|
||||
Assert.Empty(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenCollectionIsEmpty_ShouldReturnNoErrors()
|
||||
{
|
||||
// Arrange
|
||||
_sut.Must(item => item.Length > 0);
|
||||
TestRequest request = new()
|
||||
{
|
||||
Items = []
|
||||
};
|
||||
|
||||
// Act
|
||||
List<Error> result = [.. _sut.Validate(request)];
|
||||
|
||||
// Assert
|
||||
Assert.Empty(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenAllItemsSatisfyPredicate_ShouldReturnNoErrors()
|
||||
{
|
||||
// Arrange
|
||||
_sut.Must(item => item.Length > 0);
|
||||
TestRequest request = new()
|
||||
{
|
||||
Items = ["alpha", "beta"]
|
||||
};
|
||||
|
||||
// Act
|
||||
List<Error> result = [.. _sut.Validate(request)];
|
||||
|
||||
// Assert
|
||||
Assert.Empty(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenPredicateFailsOnSomeItems_ShouldReturnErrorForEachFailingItem()
|
||||
{
|
||||
// Arrange
|
||||
_sut.Must(item => item.Length > 0);
|
||||
TestRequest request = new()
|
||||
{
|
||||
Items = ["alpha", "", "beta"]
|
||||
};
|
||||
|
||||
// Act
|
||||
List<Error> result = [.. _sut.Validate(request)];
|
||||
|
||||
// Assert
|
||||
Error error = Assert.Single(result);
|
||||
Assert.Equal(Error.Validation(), error);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenPredicateFailsOnMultipleItems_ShouldReturnOneErrorPerItem()
|
||||
{
|
||||
// Arrange
|
||||
_sut.Must(item => item.Length > 0);
|
||||
TestRequest request = new()
|
||||
{
|
||||
Items = ["", ""]
|
||||
};
|
||||
|
||||
// Act
|
||||
List<Error> result = [.. _sut.Validate(request)];
|
||||
|
||||
// Assert
|
||||
Assert.Equal(2, result.Count);
|
||||
Assert.All(result, error => Assert.Equal(Error.Validation(), error));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenMultiplePredicatesFailOnSameItem_ShouldReturnErrorForEachFailingPredicate()
|
||||
{
|
||||
// Arrange
|
||||
_sut.Must(item => item.Length > 3);
|
||||
_sut.Must(item => item.StartsWith('x'));
|
||||
TestRequest request = new()
|
||||
{
|
||||
Items = ["ab"]
|
||||
};
|
||||
|
||||
// Act
|
||||
List<Error> result = [.. _sut.Validate(request)];
|
||||
|
||||
// Assert
|
||||
Assert.Equal(2, result.Count);
|
||||
Assert.All(result, error => Assert.Equal(Error.Validation(), error));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenInstanceAwarePredicateFails_ShouldReturnErrorForEachFailingItem()
|
||||
{
|
||||
// Arrange
|
||||
_sut.Must((request, item) => item != request.ForbiddenItem);
|
||||
TestRequest request = new()
|
||||
{
|
||||
Items = ["forbidden", "allowed"],
|
||||
ForbiddenItem = "forbidden"
|
||||
};
|
||||
|
||||
// Act
|
||||
List<Error> result = [.. _sut.Validate(request)];
|
||||
|
||||
// Assert
|
||||
Error error = Assert.Single(result);
|
||||
Assert.Equal(Error.Validation(), error);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenInstanceAwarePredicatePasses_ShouldReturnNoErrors()
|
||||
{
|
||||
// Arrange
|
||||
_sut.Must((request, item) => item != request.ForbiddenItem);
|
||||
TestRequest request = new()
|
||||
{
|
||||
Items = ["allowed", "alsoAllowed"],
|
||||
ForbiddenItem = "forbidden"
|
||||
};
|
||||
|
||||
// Act
|
||||
List<Error> result = [.. _sut.Validate(request)];
|
||||
|
||||
// Assert
|
||||
Assert.Empty(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenConditionEvaluatesToFalse_ShouldSkipValidation()
|
||||
{
|
||||
// Arrange
|
||||
_sut.When(request => request.ShouldValidate)
|
||||
.Must(item => item.Length > 0);
|
||||
TestRequest request = new()
|
||||
{
|
||||
Items = [""],
|
||||
ShouldValidate = false
|
||||
};
|
||||
|
||||
// Act
|
||||
List<Error> result = [.. _sut.Validate(request)];
|
||||
|
||||
// Assert
|
||||
Assert.Empty(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenConditionEvaluatesToTrue_ShouldRunPredicates()
|
||||
{
|
||||
// Arrange
|
||||
_sut.When(request => request.ShouldValidate)
|
||||
.Must(item => item.Length > 0);
|
||||
TestRequest request = new()
|
||||
{
|
||||
Items = [""],
|
||||
ShouldValidate = true
|
||||
};
|
||||
|
||||
// Act
|
||||
List<Error> result = [.. _sut.Validate(request)];
|
||||
|
||||
// Assert
|
||||
Error error = Assert.Single(result);
|
||||
Assert.Equal(Error.Validation(), error);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenWithErrorConfiguredForPlainPredicate_ShouldReturnConfiguredError()
|
||||
{
|
||||
// Arrange
|
||||
_sut.Must(item => item.Length > 0)
|
||||
.WithError(Error.Validation(description: "Item must not be empty."));
|
||||
TestRequest request = new()
|
||||
{
|
||||
Items = [""]
|
||||
};
|
||||
|
||||
// Act
|
||||
List<Error> result = [.. _sut.Validate(request)];
|
||||
|
||||
// Assert
|
||||
Error error = Assert.Single(result);
|
||||
Assert.Equal(Error.Validation(description: "Item must not be empty."), error);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenWithErrorConfiguredForInstanceAwarePredicate_ShouldReturnConfiguredError()
|
||||
{
|
||||
// Arrange
|
||||
_sut.Must((request, item) => item != request.ForbiddenItem)
|
||||
.WithError(Error.Validation(description: "Item is forbidden."));
|
||||
TestRequest request = new()
|
||||
{
|
||||
Items = ["forbidden"],
|
||||
ForbiddenItem = "forbidden"
|
||||
};
|
||||
|
||||
// Act
|
||||
List<Error> result = [.. _sut.Validate(request)];
|
||||
|
||||
// Assert
|
||||
Error error = Assert.Single(result);
|
||||
Assert.Equal(Error.Validation(description: "Item is forbidden."), error);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenWithErrorConfiguredBeforeAnyPredicate_ShouldApplyToNextAddedPredicate()
|
||||
{
|
||||
// Arrange
|
||||
_sut.WithError(Error.Validation(description: "Configured before predicate."))
|
||||
.Must(item => item.Length > 0);
|
||||
TestRequest request = new()
|
||||
{
|
||||
Items = [""]
|
||||
};
|
||||
|
||||
// Act
|
||||
List<Error> result = [.. _sut.Validate(request)];
|
||||
|
||||
// Assert
|
||||
Error error = Assert.Single(result);
|
||||
Assert.Equal(Error.Validation(description: "Configured before predicate."), error);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenWithErrorReceivesNonValidationError_ShouldReturnValidationErrorWithSameDescription()
|
||||
{
|
||||
// Arrange
|
||||
_sut.Must(item => item.Length > 0)
|
||||
.WithError(Error.NotFound(description: "Item is missing."));
|
||||
TestRequest request = new()
|
||||
{
|
||||
Items = [""]
|
||||
};
|
||||
|
||||
// Act
|
||||
List<Error> result = [.. _sut.Validate(request)];
|
||||
|
||||
// Assert
|
||||
Error error = Assert.Single(result);
|
||||
Assert.Equal(Error.Validation(description: "Item is missing."), error);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenChildRuleFailsOnItem_ShouldReturnChildValidationError()
|
||||
{
|
||||
// Arrange
|
||||
_sut.ChildRules(childValidator => childValidator.RuleFor(item => item.Length).Must(length => length >= 3));
|
||||
TestRequest request = new()
|
||||
{
|
||||
Items = ["ab"]
|
||||
};
|
||||
|
||||
// Act
|
||||
List<Error> result = [.. _sut.Validate(request)];
|
||||
|
||||
// Assert
|
||||
Error error = Assert.Single(result);
|
||||
Assert.Equal(Error.Validation(), error);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenChildRuleFailsOnMultipleItems_ShouldReturnOneErrorPerItem()
|
||||
{
|
||||
// Arrange
|
||||
_sut.ChildRules(childValidator => childValidator.RuleFor(item => item.Length).Must(length => length >= 3));
|
||||
TestRequest request = new()
|
||||
{
|
||||
Items = ["a", "bb"]
|
||||
};
|
||||
|
||||
// Act
|
||||
List<Error> result = [.. _sut.Validate(request)];
|
||||
|
||||
// Assert
|
||||
Assert.Equal(2, result.Count);
|
||||
Assert.All(result, error => Assert.Equal(Error.Validation(), error));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenAllItemsPassChildRule_ShouldReturnNoErrors()
|
||||
{
|
||||
// Arrange
|
||||
_sut.ChildRules(childValidator => childValidator.RuleFor(item => item.Length).Must(length => length >= 3));
|
||||
TestRequest request = new()
|
||||
{
|
||||
Items = ["abc", "defg"]
|
||||
};
|
||||
|
||||
// Act
|
||||
List<Error> result = [.. _sut.Validate(request)];
|
||||
|
||||
// Assert
|
||||
Assert.Empty(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenChildRuleConfiguredAndCollectionContainsNullItem_ShouldSkipNullItem()
|
||||
{
|
||||
// Arrange
|
||||
_sut.ChildRules(childValidator => childValidator.RuleFor(item => item.Length).Must(length => length >= 1));
|
||||
TestRequest request = new()
|
||||
{
|
||||
Items = ["a", null!]
|
||||
};
|
||||
|
||||
// Act
|
||||
List<Error> result = [.. _sut.Validate(request)];
|
||||
|
||||
// Assert
|
||||
Assert.Empty(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Test request type used to exercise the <see cref="ValidationRuleForEach{TRequest, TItem}"/> rule.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
private sealed class TestRequest
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the collection of string items validated by the rule under test.
|
||||
/// </summary>
|
||||
public List<string>? Items { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the rule condition should allow validation to run.
|
||||
/// </summary>
|
||||
public bool ShouldValidate { get; init; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the value used by the instance-aware predicate to identify forbidden items.
|
||||
/// </summary>
|
||||
public string ForbiddenItem { get; init; } = "forbidden";
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user