diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/HealthChecks/ApiReachabilityHealthCheckTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/HealthChecks/ApiReachabilityHealthCheckTests.cs new file mode 100644 index 00000000..d4998a32 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/HealthChecks/ApiReachabilityHealthCheckTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[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); + } + + /// + /// Creates a whose registration points at the given health check. + /// + /// The health check to register in the context. + /// The created instance. + private static HealthCheckContext CreateHealthCheckContext(IHealthCheck healthCheck) + { + // the ApiReachabilityHealthCheck never reads the registration, so a bare context is sufficient + return new HealthCheckContext(); + } + + /// + /// Creates the system under test configured with the provided message handler and a fixed server configuration. + /// + /// The message handler backing the inner . + /// The created . + private ApiReachabilityHealthCheck CreateSut(TestApiHttpMessageHandler messageHandler) + { + HttpClient httpClient = new(messageHandler); + IHttpClientFactory httpClientFactory = Substitute.For(); + httpClientFactory.CreateClient().Returns(httpClient); + IOptionsSnapshot serverConfigurationOptions = Substitute.For>(); + serverConfigurationOptions.Value.Returns(_serverConfigurationDtoFixture.Create(apiVersion: '1', baseAddress: "http://localhost", port: 5214)); + return new ApiReachabilityHealthCheck(httpClientFactory, serverConfigurationOptions); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Middlewares/ExceptionHandlingMiddlewareTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Middlewares/ExceptionHandlingMiddlewareTests.cs new file mode 100644 index 00000000..cd7baeb9 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Middlewares/ExceptionHandlingMiddlewareTests.cs @@ -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; + +/// +/// 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_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(), + Arg.Any(), + Arg.Is(exception => exception is InvalidOperationException && exception.Message == "Unexpected failure"), + Arg.Any>()); + } + + [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()); + } + + [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()); + } + + [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()); + } + + [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()); + } + + [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(), Arg.Any()); + 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); + } + + /// + /// Creates a with a writable response body and optional API/user/culture/service configuration. + /// + /// Whether the request accepts JSON, making it an API request. + /// The culture route value, when no route value is present. + /// The user associated with the context, for anonymous requests. + /// The request services, to leave the default provider in place. + /// The configured instance. + 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; + } + + /// + /// Creates a service provider that resolves the mocked . + /// + /// The configured instance. + private IServiceProvider CreateServiceProvider() + { + ServiceCollection services = new(); + services.AddSingleton(_mockAuthenticationService); + return services.BuildServiceProvider(); + } + + /// + /// Creates an authenticated user principal with a name identifier claim. + /// + /// The created instance. + private static ClaimsPrincipal CreateAuthenticatedUser() + { + return new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString())], "TestAuthentication")); + } + + /// + /// Reads the current response body of the provided HTTP context. + /// + /// The HTTP context whose response body is read. + /// The response body content. + private static async Task ReadResponseBodyAsync(HttpContext httpContext) + { + httpContext.Response.Body.Position = 0; + using StreamReader reader = new(httpContext.Response.Body, Encoding.UTF8); + return await reader.ReadToEndAsync(); + } + + /// + /// Reads the errorMessage property from the JSON response body of the provided HTTP context. + /// + /// The HTTP context whose JSON response body is read. + /// The value of the errorMessage property. + private static async Task ReadErrorMessageAsync(HttpContext httpContext) + { + string body = await ReadResponseBodyAsync(httpContext); + using JsonDocument jsonDocument = JsonDocument.Parse(body); + return jsonDocument.RootElement.GetProperty("errorMessage").GetString() ?? string.Empty; + } + + /// + /// Deserializes a problem details payload that contains a validation errors extension object. + /// + /// The deserialized instance. + 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(problemDetailsJson)!; + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Middlewares/NotFoundRedirectMiddlewareTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Middlewares/NotFoundRedirectMiddlewareTests.cs new file mode 100644 index 00000000..c40be59e --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Middlewares/NotFoundRedirectMiddlewareTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class NotFoundRedirectMiddlewareTests +{ + private readonly ILogger _mockLogger; + private readonly NotFoundRedirectMiddleware _sut; + private RequestDelegate _nextDelegate; + + /// + /// Initializes a new instance of the class. + /// + public NotFoundRedirectMiddlewareTests() + { + _mockLogger = Substitute.For>(); + _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(); + requestCultureFeature.RequestCulture.Returns(new RequestCulture("fr-FR")); + httpContext.Features.Set(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(new StartedHttpResponseFeature()); + + // Act + await _sut.InvokeAsync(httpContext); + + // Assert + Assert.Equal(1, invocationCount); + Assert.Equal("/en-us/books/123", httpContext.Request.Path.Value); + } + + /// + /// Creates a with a writable response body and an optional culture route value. + /// + /// The culture route value, when no route value is present. + /// The configured instance. + 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; + } + + /// + /// Response feature that reports the response as already started, for simulating a response that cannot be replaced. + /// + private sealed class StartedHttpResponseFeature : IHttpResponseFeature + { + /// + /// Gets or sets the HTTP status code of the response. + /// + public int StatusCode { get; set; } = StatusCodes.Status200OK; + + /// + /// Gets or sets the reason phrase of the response. + /// + public string? ReasonPhrase { get; set; } + + /// + /// Gets or sets the response headers. + /// + public IHeaderDictionary Headers { get; set; } = new HeaderDictionary(); + + /// + /// Gets or sets the response body stream. + /// + public Stream Body { get; set; } = Stream.Null; + + /// + /// Gets a value indicating whether the response has already started. + /// + public bool HasStarted => true; + + /// + /// Registers a callback to be invoked when the response is about to start. + /// + /// The callback to invoke. + /// The state passed to the callback. + public void OnStarting(Func callback, object state) + { + } + + /// + /// Registers a callback to be invoked when the response has completed. + /// + /// The callback to invoke. + /// The state passed to the callback. + public void OnCompleted(Func callback, object state) + { + } + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Services/CachedAuthorizationHandlerTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Services/CachedAuthorizationHandlerTests.cs new file mode 100644 index 00000000..2e19bbad --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Services/CachedAuthorizationHandlerTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[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; + + /// + /// Initializes a new instance of the class. + /// + public CachedAuthorizationHandlerTests() + { + ServiceCollection services = new(); + services.AddHybridCache(); + _hybridCache = services.BuildServiceProvider().GetRequiredService(); + } + + [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); + } + + /// + /// Creates an that pipes requests through a backed by the given inner handler. + /// + /// The user id claim placed on the current HTTP context user, for anonymous requests. + /// The message handler backing the inner pipeline. + /// The created . + private HttpClient CreateClient(Guid? userId, TestApiHttpMessageHandler messageHandler) + { + IHttpContextAccessor httpContextAccessor = Substitute.For(); + 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); + } + + /// + /// Creates an with the given status code and JSON body. + /// + /// The HTTP status code of the response. + /// The JSON payload of the response body. + /// The created . + private static HttpResponseMessage CreateJsonResponse(HttpStatusCode statusCode, string json) + { + return new HttpResponseMessage(statusCode) + { + Content = new StringContent(json, Encoding.UTF8, "application/json") + }; + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Validation/ValidationOptionsTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Validation/ValidationOptionsTests.cs new file mode 100644 index 00000000..466a7c72 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Validation/ValidationOptionsTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ValidationOptionsTests +{ + [Fact] + public void Validate_WhenMatchingName_ShouldValidateOptions() + { + // Arrange + string optionsName = "OptionsName"; + TestOptions options = new(); + IValidator validator = Substitute.For>(); + validator.Validate(options).Returns([]); + ValidationOptions sut = new(optionsName, validator); + + // Act + ValidateOptionsResult result = sut.Validate(optionsName, options); + + // Assert + Assert.IsType(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 validator = Substitute.For>(); + ValidationOptions 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 validator = Substitute.For>(); + validator.Validate(options).Returns([]); + ValidationOptions sut = new(null, validator); + + // Act + ValidateOptionsResult result = sut.Validate("AnyOptionsName", options); + + // Assert + Assert.IsType(result); + Assert.False(result.Failed); + validator.Received(1).Validate(options); + } + + [Fact] + public void Validate_WhenNullOptions_ShouldThrowArgumentNullException() + { + // Arrange + string optionsName = "OptionsName"; + IValidator validator = Substitute.For>(); + ValidationOptions sut = new(optionsName, validator); + + // Act + Action act = () => sut.Validate(optionsName, null!); + + // Assert + Assert.Throws(act); + validator.DidNotReceive().Validate(Arg.Any()); + } + + [Fact] + public void Validate_WhenInvalidOptions_ShouldReturnFailureResult() + { + // Arrange + string optionsName = "OptionsName"; + TestOptions options = new(); + IValidator validator = Substitute.For>(); + List validationFailures = + [ + Error.Validation("PropertyName", "Error Message") + ]; + validator.Validate(options).Returns(validationFailures); + ValidationOptions sut = new(optionsName, validator); + + // Act + ValidateOptionsResult result = sut.Validate(optionsName, options); + + // Assert + Assert.IsType(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 validator = Substitute.For>(); + List validationFailures = + [ + Error.Validation("PropertyOne", "First Error Message"), + Error.Validation("PropertyTwo", "Second Error Message") + ]; + validator.Validate(options).Returns(validationFailures); + ValidationOptions sut = new(optionsName, validator); + + // Act + ValidateOptionsResult result = sut.Validate(optionsName, options); + + // Assert + Assert.IsType(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); + } + + /// + /// Placeholder options type used to exercise the generic class. + /// + [ExcludeFromCodeCoverage] + public sealed class TestOptions + { + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Validation/ValidationRuleForEachTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Validation/ValidationRuleForEachTests.cs new file mode 100644 index 00000000..35b4a282 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Validation/ValidationRuleForEachTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ValidationRuleForEachTests +{ + private readonly ValidationRuleForEach _sut; + + /// + /// Initializes a new instance of the class. + /// + public ValidationRuleForEachTests() + { + _sut = new ValidationRuleForEach(request => request.Items); + } + + [Fact] + public void Validate_WhenNoPredicatesConfigured_ShouldReturnNoErrors() + { + // Arrange + TestRequest request = new() + { + Items = ["value"] + }; + + // Act + List 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 result = [.. _sut.Validate(request)]; + + // Assert + Assert.Empty(result); + } + + /// + /// Test request type used to exercise the rule. + /// + [ExcludeFromCodeCoverage] + private sealed class TestRequest + { + /// + /// Gets the collection of string items validated by the rule under test. + /// + public List? Items { get; init; } + + /// + /// Gets a value indicating whether the rule condition should allow validation to run. + /// + public bool ShouldValidate { get; init; } = true; + + /// + /// Gets the value used by the instance-aware predicate to identify forbidden items. + /// + public string ForbiddenItem { get; init; } = "forbidden"; + } +}