Renames project paths from Lumina to Nemera

This commit is contained in:
BinaryAlley committed 2026-11-27 15:34:43 +02:00
1 parent ce6fddb4c9
commit 0f659a4877
6450 files changed

No files matched your search

@@ -0,0 +1,277 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.Common;
using Lumina.Presentation.Web.Common.DTO.Configuration;
using Lumina.Presentation.Web.Common.DTO.FileSystemManagement;
using Lumina.Presentation.Web.Common.Exceptions;
using Lumina.Presentation.Web.Fixtures.Common.Api;
using Lumina.Presentation.Web.Fixtures.Common.DTO.Configuration;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
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.Api;
/// <summary>
/// Contains unit tests for the <see cref="ApiHttpClient"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ApiHttpClientTests
{
private readonly ServerConfigurationDtoFixture _serverConfigurationDtoFixture = new();
[Fact]
public async Task GetAsync_WhenApiReturnsSuccess_ShouldDeserializeResponseContent()
{
// Arrange
TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.OK, """[{"title":"Library One"}]"""));
ApiHttpClient sut = CreateSut(messageHandler);
// Act
Web.Common.DTO.Libraries.LibraryDto[] result = await sut.GetAsync<Web.Common.DTO.Libraries.LibraryDto[]>("libraries", CancellationToken.None);
// Assert
Assert.Single(result);
Assert.Equal("Library One", result[0].Title);
Assert.Equal(new Uri("http://localhost:5214/api/v1/libraries"), messageHandler.Requests[0].RequestUri);
}
[Fact]
public async Task GetAsync_WhenApiReturnsError_ShouldThrowApiExceptionWithProblemDetails()
{
// Arrange
string problemDetailsJson = """
{
"type": "https://tools.ietf.org/html/rfc4918#section-11.2",
"title": "General.Validation",
"status": 422,
"detail": "OneOrMoreValidationErrorsOccurred"
}
""";
TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.UnprocessableEntity, problemDetailsJson));
ApiHttpClient sut = CreateSut(messageHandler);
// Act
ApiException exception = await Assert.ThrowsAsync<ApiException>(() => sut.GetAsync<object>("libraries", CancellationToken.None));
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, exception.HttpStatusCode);
Assert.NotNull(exception.ProblemDetails);
Assert.Equal("General.Validation", exception.ProblemDetails!.Title);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, exception.ProblemDetails.Status);
Assert.Equal("OneOrMoreValidationErrorsOccurred", exception.ProblemDetails.Detail);
}
[Fact]
public async Task GetAsync_WhenApiReturnsEmptyContent_ShouldReturnDefault()
{
// Arrange
TestApiHttpMessageHandler messageHandler = new(_ => new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(string.Empty) });
ApiHttpClient sut = CreateSut(messageHandler);
// Act
object? result = await sut.GetAsync<object>("libraries", CancellationToken.None);
// Assert
Assert.Null(result);
}
[Fact]
public async Task GetAsync_WhenUserHasTokenClaim_ShouldSendAuthorizationHeader()
{
// Arrange
TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.OK, "{}"));
ApiHttpClient sut = CreateSut(messageHandler, token: "test-jwt-token");
// Act
await sut.GetAsync<object>("libraries", CancellationToken.None);
// Assert
Assert.Equal("Bearer", messageHandler.Requests[0].Headers.Authorization!.Scheme);
Assert.Equal("test-jwt-token", messageHandler.Requests[0].Headers.Authorization!.Parameter);
}
[Fact]
public async Task PostAsync_WhenCalled_ShouldSerializePayloadAndDeserializeResponse()
{
// Arrange
TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.OK, """{"success":true}"""));
ApiHttpClient sut = CreateSut(messageHandler);
// Act
SuccessResponse result = await sut.PostAsync<SuccessResponse, object>("auth/login", new { username = "testuser" }, CancellationToken.None);
// Assert
Assert.True(result.IsSuccess);
Assert.Equal(HttpMethod.Post, messageHandler.Requests[0].Method);
Assert.Equal("http://localhost:5214/api/v1/auth/login", messageHandler.Requests[0].RequestUri!.ToString());
Assert.Contains("testuser", messageHandler.RequestBodies[0]);
}
[Fact]
public async Task PostAsync_WhenCalledWithoutPayload_ShouldDeserializeResponse()
{
// Arrange
TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.OK, """{"success":true}"""));
ApiHttpClient sut = CreateSut(messageHandler);
// Act
SuccessResponse result = await sut.PostAsync<SuccessResponse>("libraries", CancellationToken.None);
// Assert
Assert.True(result.IsSuccess);
Assert.Equal(HttpMethod.Post, messageHandler.Requests[0].Method);
Assert.Null(messageHandler.Requests[0].Content);
}
[Fact]
public async Task PostIgnoringResponseAsync_WhenCalledWithoutPayload_ShouldSendBodylessRequestAndIgnoreNonEmptyResponse()
{
// Arrange
TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.OK, "{}"));
ApiHttpClient sut = CreateSut(messageHandler);
// Act
await sut.PostIgnoringResponseAsync("libraries/1", CancellationToken.None);
// Assert
Assert.Equal(HttpMethod.Post, messageHandler.Requests[0].Method);
Assert.Null(messageHandler.Requests[0].Content);
}
[Fact]
public async Task PostIgnoringResponseAsync_WhenUserHasTokenClaim_ShouldSendAuthorizationHeader()
{
// Arrange
TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.OK, "{}"));
ApiHttpClient sut = CreateSut(messageHandler, token: "test-jwt-token");
// Act
await sut.PostIgnoringResponseAsync("libraries/1", CancellationToken.None);
// Assert
Assert.Equal("Bearer", messageHandler.Requests[0].Headers.Authorization!.Scheme);
Assert.Equal("test-jwt-token", messageHandler.Requests[0].Headers.Authorization!.Parameter);
}
[Fact]
public async Task PutIgnoringResponseAsync_WhenCalledWithPayload_ShouldSerializePayloadAndIgnoreNonEmptyResponse()
{
// Arrange
TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.OK, """{"updated":true}"""));
ApiHttpClient sut = CreateSut(messageHandler);
// Act
await sut.PutIgnoringResponseAsync("libraries/1", new { title = "Library One" }, CancellationToken.None);
// Assert
Assert.Contains("Library One", messageHandler.RequestBodies[0]);
}
[Fact]
public async Task PostIgnoringResponseAsync_WhenApiReturnsError_ShouldThrowApiExceptionWithProblemDetails()
{
// Arrange
string problemDetailsJson = """
{
"type": "https://tools.ietf.org/html/rfc9110#section-15.6.1",
"title": "General.Failure",
"status": 500,
"detail": "UnexpectedFailure"
}
""";
TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.InternalServerError, problemDetailsJson));
ApiHttpClient sut = CreateSut(messageHandler);
// Act
ApiException exception = await Assert.ThrowsAsync<ApiException>(() => sut.PostIgnoringResponseAsync("libraries/1", CancellationToken.None));
// Assert
Assert.Equal(HttpStatusCode.InternalServerError, exception.HttpStatusCode);
Assert.NotNull(exception.ProblemDetails);
Assert.Equal("General.Failure", exception.ProblemDetails!.Title);
Assert.Equal("UnexpectedFailure", exception.ProblemDetails.Detail);
}
[Fact]
public async Task DeleteAsync_WhenApiReturnsError_ShouldThrowApiException()
{
// Arrange
TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.InternalServerError, """{"title":"General.Failure","status":500}"""));
ApiHttpClient sut = CreateSut(messageHandler);
// Act
ApiException exception = await Assert.ThrowsAsync<ApiException>(() => sut.DeleteAsync("libraries/1", CancellationToken.None));
// Assert
Assert.Equal(HttpStatusCode.InternalServerError, exception.HttpStatusCode);
Assert.Equal("/api/v1/libraries/1", exception.RequestPath);
}
[Fact]
public async Task GetBlobAsync_WhenApiReturnsSuccess_ShouldReturnBlobData()
{
// Arrange
byte[] imageBytes = Encoding.UTF8.GetBytes("fake-image-bytes");
TestApiHttpMessageHandler messageHandler = new(_ =>
{
HttpResponseMessage response = new(HttpStatusCode.OK) { Content = new ByteArrayContent(imageBytes) };
response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/png");
return response;
});
ApiHttpClient sut = CreateSut(messageHandler);
// Act
BlobDataDto blob = await sut.GetBlobAsync("libraries/1/cover", CancellationToken.None);
// Assert
Assert.Equal(imageBytes, blob.Data);
Assert.Equal("image/png", blob.ContentType);
}
/// <summary>
/// Creates the system under test configured with the provided message handler.
/// </summary>
/// <param name="messageHandler">The message handler backing the inner <see cref="HttpClient"/>.</param>
/// <param name="token">Optional token claim to place on the current HTTP context user.</param>
/// <returns>The created <see cref="ApiHttpClient"/>.</returns>
private ApiHttpClient CreateSut(TestApiHttpMessageHandler messageHandler, string? token = null)
{
HttpClient httpClient = new(messageHandler);
IHttpContextAccessor httpContextAccessor = Substitute.For<IHttpContextAccessor>();
if (token is not null)
{
DefaultHttpContext httpContext = new()
{
User = new ClaimsPrincipal(new ClaimsIdentity([new Claim("Token", token)], "TestAuthentication"))
};
httpContextAccessor.HttpContext.Returns(httpContext);
}
IOptionsSnapshot<ServerConfigurationDto> serverConfigurationOptions = Substitute.For<IOptionsSnapshot<ServerConfigurationDto>>();
serverConfigurationOptions.Value.Returns(_serverConfigurationDtoFixture.Create(apiVersion: '1', baseAddress: "http://localhost", port: 5214));
return new ApiHttpClient(httpClient, httpContextAccessor, serverConfigurationOptions);
}
/// <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")
};
}
}
@@ -0,0 +1,196 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Api;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Common.Api;
/// <summary>
/// Contains unit tests for the <see cref="ApiStreamResult"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ApiStreamResultTests
{
/// <summary>
/// Initializes a new instance of the <see cref="ApiStreamResultTests"/> class.
/// </summary>
public ApiStreamResultTests()
{
}
[Fact]
public async Task CreateAsync_WhenResponseDeclaresHeaders_ShouldExposeTheStatusAndTheContentHeaders()
{
// Arrange
byte[] contentBytes = CreateBytes(64);
using HttpResponseMessage response = CreateResponse(contentBytes);
response.Content.Headers.ContentRange = new ContentRangeHeaderValue(0, contentBytes.Length - 1, 1024);
response.Headers.AcceptRanges.Add("bytes");
response.Headers.ETag = new EntityTagHeaderValue("\"etag-value\"");
DateTimeOffset lastModified = new(2026, 1, 2, 3, 4, 5, TimeSpan.Zero);
response.Content.Headers.LastModified = lastModified;
response.Headers.CacheControl = new CacheControlHeaderValue { Public = true, MaxAge = TimeSpan.FromSeconds(60) };
// Act
await using ApiStreamResult result = await ApiStreamResult.CreateAsync(response, CancellationToken.None);
// Assert
Assert.Equal(HttpStatusCode.PartialContent, result.StatusCode);
Assert.Equal("audio/mp4", result.ContentType);
Assert.Equal(contentBytes.Length, result.ContentLength);
Assert.Equal("bytes 0-63/1024", result.ContentRange);
Assert.Equal("bytes", result.AcceptRanges);
Assert.Equal("\"etag-value\"", result.ETag);
Assert.Equal(lastModified, result.LastModified);
Assert.Contains("max-age=60", result.CacheControl);
}
[Theory]
[InlineData("0")] // An empty production reports zero segments.
[InlineData("1")] // A single segment production.
[InlineData("42")] // A multi segment production.
public async Task CreateAsync_WhenSegmentCountIsValid_ShouldExposeIt(string segmentCount)
{
// Arrange
using HttpResponseMessage response = CreateResponse(CreateBytes(8));
response.Headers.TryAddWithoutValidation(ApiStreamResult.SEGMENT_COUNT_HEADER_NAME, segmentCount);
// Act
await using ApiStreamResult result = await ApiStreamResult.CreateAsync(response, CancellationToken.None);
// Assert
Assert.Equal(int.Parse(segmentCount), result.SegmentCount);
}
[Theory]
[InlineData(null)] // The header is absent.
[InlineData("")] // The header is empty.
[InlineData("not-a-number")] // The header is malformed.
[InlineData("-1")] // A negative count is treated as absent.
[InlineData("1.5")] // A fractional count is treated as absent.
public async Task CreateAsync_WhenSegmentCountIsInvalid_ShouldReturnNull(string? segmentCount)
{
// Arrange
using HttpResponseMessage response = CreateResponse(CreateBytes(8));
if (segmentCount is not null)
response.Headers.TryAddWithoutValidation(ApiStreamResult.SEGMENT_COUNT_HEADER_NAME, segmentCount);
// Act
await using ApiStreamResult result = await ApiStreamResult.CreateAsync(response, CancellationToken.None);
// Assert
Assert.Null(result.SegmentCount);
}
[Theory]
[InlineData("0")] // The first segment starts at the beginning of the track.
[InlineData("6.5")] // A decimal with a dot is forwarded as the API wrote it.
[InlineData("6,5")] // A decimal with a comma, which is not the invariant separator, is still forwarded verbatim.
public async Task CreateAsync_WhenSegmentStartIsPresent_ShouldForwardItVerbatim(string segmentStart)
{
// Arrange
using HttpResponseMessage response = CreateResponse(CreateBytes(8));
response.Headers.TryAddWithoutValidation(ApiStreamResult.SEGMENT_START_SECONDS_HEADER_NAME, segmentStart);
// Act
await using ApiStreamResult result = await ApiStreamResult.CreateAsync(response, CancellationToken.None);
// Assert
Assert.Equal(segmentStart, result.SegmentStartSeconds);
}
[Fact]
public async Task CreateAsync_WhenSegmentStartIsAbsent_ShouldReturnNull()
{
// Arrange
using HttpResponseMessage response = CreateResponse(CreateBytes(8));
// Act
await using ApiStreamResult result = await ApiStreamResult.CreateAsync(response, CancellationToken.None);
// Assert
Assert.Null(result.SegmentStartSeconds);
}
[Theory]
[InlineData("1")] // A one second production.
[InlineData("300")] // A five minute production.
public async Task CreateAsync_WhenTrackDurationIsPositive_ShouldExposeIt(string trackDuration)
{
// Arrange
using HttpResponseMessage response = CreateResponse(CreateBytes(8));
response.Headers.TryAddWithoutValidation(ApiStreamResult.TRACK_DURATION_SECONDS_HEADER_NAME, trackDuration);
// Act
await using ApiStreamResult result = await ApiStreamResult.CreateAsync(response, CancellationToken.None);
// Assert
Assert.Equal(int.Parse(trackDuration), result.TrackDurationSeconds);
}
[Theory]
[InlineData(null)] // The header is absent.
[InlineData("0")] // A zero duration is treated as absent.
[InlineData("-5")] // A negative duration is treated as absent.
[InlineData("not-a-number")] // The header is malformed.
public async Task CreateAsync_WhenTrackDurationIsInvalid_ShouldReturnNull(string? trackDuration)
{
// Arrange
using HttpResponseMessage response = CreateResponse(CreateBytes(8));
if (trackDuration is not null)
response.Headers.TryAddWithoutValidation(ApiStreamResult.TRACK_DURATION_SECONDS_HEADER_NAME, trackDuration);
// Act
await using ApiStreamResult result = await ApiStreamResult.CreateAsync(response, CancellationToken.None);
// Assert
Assert.Null(result.TrackDurationSeconds);
}
[Fact]
public async Task DisposeAsync_WhenCalled_ShouldDisposeTheContentStreamAndTheResponse()
{
// Arrange
HttpResponseMessage response = CreateResponse(CreateBytes(16));
ApiStreamResult result = await ApiStreamResult.CreateAsync(response, CancellationToken.None);
// Act
await result.DisposeAsync();
// Assert
Assert.Throws<ObjectDisposedException>(() => result.Content.ReadByte());
await Assert.ThrowsAsync<ObjectDisposedException>(() => response.Content.ReadAsByteArrayAsync());
}
/// <summary>
/// Creates a streamed API response with a media type and a partial content status.
/// </summary>
/// <param name="contentBytes">The bytes of the content of the response.</param>
/// <returns>The created HTTP response.</returns>
private static HttpResponseMessage CreateResponse(byte[] contentBytes)
{
HttpResponseMessage response = new(HttpStatusCode.PartialContent)
{
Content = new ByteArrayContent(contentBytes)
};
response.Content.Headers.ContentType = new MediaTypeHeaderValue("audio/mp4");
return response;
}
/// <summary>
/// Creates a deterministic byte array that stands in for streamed content.
/// </summary>
/// <param name="length">The number of bytes to create.</param>
/// <returns>The created bytes.</returns>
private static byte[] CreateBytes(int length)
{
return [.. Enumerable.Range(0, length).Select(index => (byte)(index % 256))];
}
}
@@ -0,0 +1,374 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.Configuration;
using Lumina.Presentation.Web.Common.Exceptions;
using Lumina.Presentation.Web.Fixtures.Common.Api;
using Lumina.Presentation.Web.Fixtures.Common.DTO.Configuration;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Claims;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Common.Api;
/// <summary>
/// Contains unit tests for the <see cref="StreamingApiHttpClient"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class StreamingApiHttpClientTests
{
private const string ENDPOINT = "libraries/tracks/1/stream";
private readonly ServerConfigurationDtoFixture _serverConfigurationDtoFixture = new();
[Fact]
public void Constructor_WhenCalled_ShouldConfigureTheBaseAddressFromTheServerConfiguration()
{
// Arrange
HttpClient httpClient = new(new TestApiHttpMessageHandler(_ => new HttpResponseMessage(HttpStatusCode.OK)));
// Act
_ = CreateSut(httpClient);
// Assert
Assert.Equal(new Uri("http://localhost:5214/api/v1/"), httpClient.BaseAddress);
}
[Fact]
public void Constructor_WhenCalled_ShouldConfigureATwelveHourTimeout()
{
// Arrange
HttpClient httpClient = new(new TestApiHttpMessageHandler(_ => new HttpResponseMessage(HttpStatusCode.OK)));
// Act
_ = CreateSut(httpClient);
// Assert
Assert.Equal(TimeSpan.FromHours(12), httpClient.Timeout);
}
[Fact]
public async Task GetStreamAsync_WhenCalled_ShouldSendAGetRequestToTheEndpoint()
{
// Arrange
TestApiHttpMessageHandler messageHandler = new(_ => CreateStreamResponse(HttpStatusCode.OK));
StreamingApiHttpClient sut = CreateSut(messageHandler);
// Act
await using ApiStreamResult result = await sut.GetStreamAsync(ENDPOINT, CreateForwardedHeaders(), CancellationToken.None);
// Assert
Assert.Equal(HttpMethod.Get, messageHandler.Requests[0].Method);
Assert.Equal(new Uri("http://localhost:5214/api/v1/libraries/tracks/1/stream"), messageHandler.Requests[0].RequestUri);
}
[Fact]
public async Task GetStreamAsync_WhenRequestHeadersProvided_ShouldForwardThemVerbatim()
{
// Arrange
TestApiHttpMessageHandler messageHandler = new(_ => CreateStreamResponse(HttpStatusCode.OK));
StreamingApiHttpClient sut = CreateSut(messageHandler);
Dictionary<string, string> requestHeaders = new()
{
["Range"] = "bytes=1024-2047",
["If-None-Match"] = "\"etag-value\"",
["If-Modified-Since"] = "Wed, 21 Oct 2026 07:28:00 GMT"
};
// Act
await using ApiStreamResult result = await sut.GetStreamAsync(ENDPOINT, requestHeaders, CancellationToken.None);
// Assert
HttpRequestMessage request = messageHandler.Requests[0];
Assert.Equal("bytes=1024-2047", request.Headers.Range!.ToString());
Assert.Equal("\"etag-value\"", Assert.Single(request.Headers.IfNoneMatch).Tag);
Assert.Equal(new DateTimeOffset(2026, 10, 21, 7, 28, 0, TimeSpan.Zero), request.Headers.IfModifiedSince);
}
[Fact]
public async Task GetStreamAsync_WhenUserHasToken_ShouldSendTheBearerToken()
{
// Arrange
TestApiHttpMessageHandler messageHandler = new(_ => CreateStreamResponse(HttpStatusCode.OK));
StreamingApiHttpClient sut = CreateSut(messageHandler, token: "test-jwt-token");
// Act
await using ApiStreamResult result = await sut.GetStreamAsync(ENDPOINT, CreateForwardedHeaders(), CancellationToken.None);
// Assert
Assert.Equal("Bearer", messageHandler.Requests[0].Headers.Authorization!.Scheme);
Assert.Equal("test-jwt-token", messageHandler.Requests[0].Headers.Authorization!.Parameter);
}
[Theory]
[InlineData(false, null)] // There is no HTTP context at all.
[InlineData(true, null)] // The HTTP context has no token claim.
[InlineData(true, "")] // The token claim is empty.
public async Task GetStreamAsync_WhenTokenIsUnavailable_ShouldNotSendAnAuthorizationHeader(bool hasHttpContext, string? token)
{
// Arrange
TestApiHttpMessageHandler messageHandler = new(_ => CreateStreamResponse(HttpStatusCode.OK));
StreamingApiHttpClient sut = CreateSut(messageHandler, token: token, hasHttpContext: hasHttpContext);
// Act
await using ApiStreamResult result = await sut.GetStreamAsync(ENDPOINT, CreateForwardedHeaders(), CancellationToken.None);
// Assert
Assert.Null(messageHandler.Requests[0].Headers.Authorization);
}
[Fact]
public async Task GetStreamAsync_WhenCalled_ShouldHandOverTheContentStreamWithoutBufferingIt()
{
// Arrange
TrackingStreamContent content = new(Encoding.UTF8.GetBytes("streamed-audio"), "audio/mp4");
TestApiHttpMessageHandler messageHandler = new(_ => new HttpResponseMessage(HttpStatusCode.OK) { Content = content });
StreamingApiHttpClient sut = CreateSut(messageHandler);
// Act
await using ApiStreamResult result = await sut.GetStreamAsync(ENDPOINT, CreateForwardedHeaders(), CancellationToken.None);
// Assert
Assert.False(content.WasBufferedByClient);
Assert.Same(content.ContentStream, result.Content);
}
[Fact]
public async Task GetStreamAsync_WhenApiReturnsOk_ShouldReturnAStreamResultWithTheContent()
{
// Arrange
byte[] contentBytes = Encoding.UTF8.GetBytes("streamed-audio");
TrackingStreamContent content = new(contentBytes, "audio/mp4");
TestApiHttpMessageHandler messageHandler = new(_ => new HttpResponseMessage(HttpStatusCode.OK) { Content = content });
StreamingApiHttpClient sut = CreateSut(messageHandler);
// Act
await using ApiStreamResult result = await sut.GetStreamAsync(ENDPOINT, CreateForwardedHeaders(), CancellationToken.None);
// Assert
Assert.Equal(HttpStatusCode.OK, result.StatusCode);
Assert.Equal("audio/mp4", result.ContentType);
Assert.Equal(contentBytes.Length, result.ContentLength);
}
[Fact]
public async Task GetStreamAsync_WhenApiReturnsPartialContent_ShouldReturnAStreamResultWithTheRangeHeaders()
{
// Arrange
byte[] contentBytes = Encoding.UTF8.GetBytes("streamed-audio-segment");
TrackingStreamContent content = new(contentBytes, "audio/mp4");
content.Headers.ContentRange = new ContentRangeHeaderValue(0, contentBytes.Length - 1, 4096);
TestApiHttpMessageHandler messageHandler = new(_ => new HttpResponseMessage(HttpStatusCode.PartialContent) { Content = content });
StreamingApiHttpClient sut = CreateSut(messageHandler);
// Act
await using ApiStreamResult result = await sut.GetStreamAsync(ENDPOINT, CreateForwardedHeaders(), CancellationToken.None);
// Assert
Assert.Equal(HttpStatusCode.PartialContent, result.StatusCode);
Assert.Equal($"bytes 0-{contentBytes.Length - 1}/4096", result.ContentRange);
Assert.Equal(contentBytes.Length, result.ContentLength);
}
[Theory]
[InlineData(HttpStatusCode.NotModified)] // A conditional request that the entity tag did not invalidate.
[InlineData(HttpStatusCode.RequestedRangeNotSatisfiable)] // A ranged request that cannot be satisfied.
public async Task GetStreamAsync_WhenApiReturnsANonSuccessThatIsAValidOutcome_ShouldPassTheResponseThrough(HttpStatusCode statusCode)
{
// Arrange
TestApiHttpMessageHandler messageHandler = new(_ => new HttpResponseMessage(statusCode));
StreamingApiHttpClient sut = CreateSut(messageHandler);
// Act
await using ApiStreamResult result = await sut.GetStreamAsync(ENDPOINT, CreateForwardedHeaders(), CancellationToken.None);
// Assert
Assert.Equal(statusCode, result.StatusCode);
}
[Theory]
[InlineData(HttpStatusCode.BadRequest)] // A malformed request.
[InlineData(HttpStatusCode.NotFound)] // The track does not exist.
[InlineData(HttpStatusCode.InternalServerError)] // The API failed.
public async Task GetStreamAsync_WhenApiReturnsAnotherNonSuccess_ShouldThrowApiExceptionWithTheProblemDetails(HttpStatusCode statusCode)
{
// Arrange
string problemDetailsJson = $$"""
{
"type": "https://tools.ietf.org/html/rfc9110#section-15.5.5",
"title": "General.NotFound",
"status": {{(int)statusCode}},
"detail": "The requested track was not found."
}
""";
TrackingStreamContent content = new(Encoding.UTF8.GetBytes(problemDetailsJson), "application/problem+json");
TestApiHttpMessageHandler messageHandler = new(_ => new HttpResponseMessage(statusCode) { Content = content });
StreamingApiHttpClient sut = CreateSut(messageHandler);
// Act
ApiException exception = await Assert.ThrowsAsync<ApiException>(() => sut.GetStreamAsync(ENDPOINT, CreateForwardedHeaders(), CancellationToken.None));
// Assert
Assert.Equal(statusCode, exception.HttpStatusCode);
Assert.NotNull(exception.ProblemDetails);
Assert.Equal("General.NotFound", exception.ProblemDetails!.Title);
Assert.Equal((int)statusCode, exception.ProblemDetails!.Status);
Assert.Equal("The requested track was not found.", exception.ProblemDetails!.Detail);
Assert.Equal("/api/v1/libraries/tracks/1/stream", exception.RequestPath);
}
[Fact]
public async Task GetStreamAsync_WhenErrorBodyIsNotProblemDetails_ShouldThrowApiExceptionWithoutProblemDetails()
{
// Arrange
TrackingStreamContent content = new(Encoding.UTF8.GetBytes("<html>upstream failure</html>"), "text/html");
TestApiHttpMessageHandler messageHandler = new(_ => new HttpResponseMessage(HttpStatusCode.BadGateway) { Content = content });
StreamingApiHttpClient sut = CreateSut(messageHandler);
// Act
ApiException exception = await Assert.ThrowsAsync<ApiException>(() => sut.GetStreamAsync(ENDPOINT, CreateForwardedHeaders(), CancellationToken.None));
// Assert
Assert.Equal(HttpStatusCode.BadGateway, exception.HttpStatusCode);
Assert.Null(exception.ProblemDetails);
Assert.Equal("An error occurred.", exception.Message);
}
[Fact]
public async Task GetStreamAsync_WhenApiReturnsANonSuccess_ShouldDisposeTheResponse()
{
// Arrange
TrackingStreamContent content = new(Encoding.UTF8.GetBytes("""{"title":"General.Failure","status":500}"""), "application/json");
TestApiHttpMessageHandler messageHandler = new(_ => new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = content });
StreamingApiHttpClient sut = CreateSut(messageHandler);
// Act
await Assert.ThrowsAsync<ApiException>(() => sut.GetStreamAsync(ENDPOINT, CreateForwardedHeaders(), CancellationToken.None));
// Assert
Assert.True(content.IsDisposed);
}
[Fact]
public async Task GetStreamAsync_WhenContentStreamCannotBeObtained_ShouldDisposeTheResponse()
{
// Arrange
TrackingStreamContent content = new(Encoding.UTF8.GetBytes("streamed-audio"), "audio/mp4", shouldFailStreamCreation: true);
TestApiHttpMessageHandler messageHandler = new(_ => new HttpResponseMessage(HttpStatusCode.OK) { Content = content });
StreamingApiHttpClient sut = CreateSut(messageHandler);
// Act
await Assert.ThrowsAsync<InvalidOperationException>(() => sut.GetStreamAsync(ENDPOINT, CreateForwardedHeaders(), CancellationToken.None));
// Assert
Assert.True(content.IsDisposed);
}
[Fact]
public async Task GetStreamAsync_WhenCancellationIsRequested_ShouldCancelTheOperation()
{
// Arrange
using CancellationTokenSource cancellationTokenSource = new();
TaskCompletionSource<bool> requestStarted = new();
TestApiHttpMessageHandler messageHandler = new(async (request, cancellationToken) =>
{
requestStarted.SetResult(true);
await Task.Delay(Timeout.Infinite, cancellationToken);
return new HttpResponseMessage(HttpStatusCode.OK);
});
StreamingApiHttpClient sut = CreateSut(messageHandler);
// Act
Task<ApiStreamResult> operationTask = sut.GetStreamAsync(ENDPOINT, CreateForwardedHeaders(), cancellationTokenSource.Token);
await requestStarted.Task;
cancellationTokenSource.Cancel();
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
Assert.True(messageHandler.CancellationTokens[0].IsCancellationRequested);
}
/// <summary>
/// Creates the system under test around the provided HTTP client.
/// </summary>
/// <param name="httpClient">The HTTP client the system under test sends its requests through.</param>
/// <returns>The created <see cref="StreamingApiHttpClient"/>.</returns>
private StreamingApiHttpClient CreateSut(HttpClient httpClient)
{
IOptionsSnapshot<ServerConfigurationDto> serverConfigurationOptions = Substitute.For<IOptionsSnapshot<ServerConfigurationDto>>();
serverConfigurationOptions.Value.Returns(_serverConfigurationDtoFixture.Create(apiVersion: '1', baseAddress: "http://localhost", port: 5214));
return new StreamingApiHttpClient(httpClient, Substitute.For<IHttpContextAccessor>(), serverConfigurationOptions);
}
/// <summary>
/// Creates the system under test configured with the provided message handler.
/// </summary>
/// <param name="messageHandler">The message handler backing the inner <see cref="HttpClient"/>.</param>
/// <param name="token">Optional token claim to place on the current HTTP context user.</param>
/// <param name="hasHttpContext">Whether an HTTP context is available to the system under test.</param>
/// <returns>The created <see cref="StreamingApiHttpClient"/>.</returns>
private StreamingApiHttpClient CreateSut(TestApiHttpMessageHandler messageHandler, string? token = null, bool hasHttpContext = true)
{
HttpClient httpClient = new(messageHandler);
IHttpContextAccessor httpContextAccessor = Substitute.For<IHttpContextAccessor>();
if (hasHttpContext)
{
Claim[] claims = token is null ? [] : [new Claim("Token", token)];
DefaultHttpContext httpContext = new()
{
User = new ClaimsPrincipal(new ClaimsIdentity(claims, "TestAuthentication"))
};
httpContextAccessor.HttpContext.Returns(httpContext);
}
return CreateSut(httpClient, httpContextAccessor);
}
/// <summary>
/// Creates the system under test around the provided HTTP client and HTTP context accessor.
/// </summary>
/// <param name="httpClient">The HTTP client the system under test sends its requests through.</param>
/// <param name="httpContextAccessor">The accessor that provides the current HTTP context.</param>
/// <returns>The created <see cref="StreamingApiHttpClient"/>.</returns>
private StreamingApiHttpClient CreateSut(HttpClient httpClient, IHttpContextAccessor httpContextAccessor)
{
IOptionsSnapshot<ServerConfigurationDto> serverConfigurationOptions = Substitute.For<IOptionsSnapshot<ServerConfigurationDto>>();
serverConfigurationOptions.Value.Returns(_serverConfigurationDtoFixture.Create(apiVersion: '1', baseAddress: "http://localhost", port: 5214));
return new StreamingApiHttpClient(httpClient, httpContextAccessor, serverConfigurationOptions);
}
/// <summary>
/// Creates the range and conditional headers an incoming streaming request forwards to the API.
/// </summary>
/// <returns>The forwarded headers.</returns>
private static Dictionary<string, string> CreateForwardedHeaders()
{
return new Dictionary<string, string>
{
["Range"] = "bytes=0-1023",
["If-None-Match"] = "\"etag-value\""
};
}
/// <summary>
/// Creates a streamed API response with the given status code and a known content stream.
/// </summary>
/// <param name="statusCode">The HTTP status code of the response.</param>
/// <returns>The created HTTP response.</returns>
private static HttpResponseMessage CreateStreamResponse(HttpStatusCode statusCode)
{
return new HttpResponseMessage(statusCode)
{
Content = new TrackingStreamContent(Encoding.UTF8.GetBytes("streamed-audio"), "audio/mp4")
};
}
}
@@ -0,0 +1,22 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Authorization;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Common.Authorization;
/// <summary>
/// Contains unit tests for the <see cref="AuthorizationPolicies"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class AuthorizationPoliciesTests
{
[Fact]
public void PolicyNames_WhenRead_ShouldMatchExpectedPolicyNames()
{
// Act & Assert
Assert.Equal("RequireAdminRole", AuthorizationPolicies.REQUIRE_ADMIN_ROLE);
Assert.Equal("RequireCreateLibrariesPermission", AuthorizationPolicies.REQUIRE_CREATE_LIBRARIES_PERMISSION);
Assert.Equal("RequireInitialization", AuthorizationPolicies.REQUIRE_INITIALIZATION);
}
}
@@ -0,0 +1,189 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Authorization;
using Lumina.Presentation.Web.Common.Enums.Authorization;
using Lumina.Presentation.Web.Common.Exceptions;
using Lumina.Presentation.Web.Common.Http;
using Lumina.Presentation.Web.Common.Responses.Authorization;
using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization;
using Microsoft.AspNetCore.Http;
using NSubstitute;
using Polly.CircuitBreaker;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Common.Authorization;
/// <summary>
/// Contains unit tests for the <see cref="AuthorizationService"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class AuthorizationServiceTests
{
private readonly IApiHttpClient _mockApiHttpClient;
private readonly AuthorizationService _sut;
private readonly Guid _userId;
private readonly DefaultHttpContext _httpContext;
private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="AuthorizationServiceTests"/> class.
/// </summary>
public AuthorizationServiceTests()
{
_userId = Guid.NewGuid();
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
IHttpContextAccessor httpContextAccessor = Substitute.For<IHttpContextAccessor>();
_httpContext = new DefaultHttpContext();
_httpContext.User = new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, _userId.ToString())], "TestAuthentication"));
httpContextAccessor.HttpContext.Returns(_httpContext);
_sut = new AuthorizationService(_mockApiHttpClient, httpContextAccessor);
}
[Fact]
public async Task HasPermissionAsync_WhenUserHasPermission_ShouldReturnTrue()
{
// Arrange
_mockApiHttpClient.GetAsync<GetAuthorizationResponse>(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(_getAuthorizationResponseFixture.Create(userId: _userId, role: "Admin", permissions: [AuthorizationPermission.CanCreateLibraries]));
// Act
bool result = await _sut.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, CancellationToken.None);
// Assert
Assert.True(result);
}
[Fact]
public async Task HasPermissionAsync_WhenUserDoesNotHavePermission_ShouldReturnFalse()
{
// Arrange
_mockApiHttpClient.GetAsync<GetAuthorizationResponse>(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(_getAuthorizationResponseFixture.Create(userId: _userId, role: "Admin", permissions: [AuthorizationPermission.CanViewUsers]));
// Act
bool result = await _sut.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, CancellationToken.None);
// Assert
Assert.False(result);
}
[Fact]
public async Task IsInRoleAsync_WhenRoleMatches_ShouldReturnTrue()
{
// Arrange
_mockApiHttpClient.GetAsync<GetAuthorizationResponse>(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(_getAuthorizationResponseFixture.Create(userId: _userId, role: "Admin", permissions: []));
// Act
bool result = await _sut.IsInRoleAsync("Admin", CancellationToken.None);
// Assert
Assert.True(result);
}
[Fact]
public async Task IsInRoleAsync_WhenRoleDoesNotMatch_ShouldReturnFalse()
{
// Arrange
_mockApiHttpClient.GetAsync<GetAuthorizationResponse>(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(_getAuthorizationResponseFixture.Create(userId: _userId, role: "User", permissions: []));
// Act
bool result = await _sut.IsInRoleAsync("Admin", CancellationToken.None);
// Assert
Assert.False(result);
}
[Fact]
public async Task HasPermissionAsync_WhenCalled_ShouldRequestAuthorizationForCurrentUser()
{
// Arrange
_mockApiHttpClient.GetAsync<GetAuthorizationResponse>(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(_getAuthorizationResponseFixture.Create(userId: _userId, role: "Admin", permissions: []));
// Act
await _sut.HasPermissionAsync(AuthorizationPermission.CanViewUsers, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).GetAsync<GetAuthorizationResponse>(
Arg.Is<string>(endpoint => endpoint.StartsWith($"auth/get-authorization?userId={_userId}", StringComparison.OrdinalIgnoreCase)),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task HasPermissionAsync_WhenTheApiIsUnreachableDuringAPageNavigation_ShouldReturnFalseAndMarkTheServerUnreachable()
{
// Arrange
_httpContext.Request.Headers.Accept = "text/html";
_mockApiHttpClient.GetAsync<GetAuthorizationResponse>(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(Task.FromException<GetAuthorizationResponse>(new BrokenCircuitException()));
// Act
bool result = await _sut.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, CancellationToken.None);
// Assert
Assert.False(result);
Assert.True(_httpContext.Items[HttpContextItemKeys.SERVER_UNREACHABLE] is true);
}
[Fact]
public async Task HasPermissionAsync_WhenTheApiIsUnreachableDuringAJsonRequest_ShouldRethrow()
{
// Arrange
_httpContext.Request.Headers.Accept = "application/json";
_mockApiHttpClient.GetAsync<GetAuthorizationResponse>(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(Task.FromException<GetAuthorizationResponse>(new BrokenCircuitException()));
// Act & Assert
await Assert.ThrowsAsync<BrokenCircuitException>(() => _sut.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, CancellationToken.None));
}
[Theory]
[InlineData(HttpStatusCode.Unauthorized)]
[InlineData(HttpStatusCode.Forbidden)]
public async Task HasPermissionAsync_WhenTheApiReturnsAnAuthorizationStatusDuringAPageNavigation_ShouldRethrow(HttpStatusCode statusCode)
{
// Arrange
_httpContext.Request.Headers.Accept = "text/html";
_mockApiHttpClient.GetAsync<GetAuthorizationResponse>(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(Task.FromException<GetAuthorizationResponse>(new ApiException(null, statusCode)));
// Act & Assert
await Assert.ThrowsAsync<ApiException>(() => _sut.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, CancellationToken.None));
}
[Fact]
public async Task HasPermissionAsync_WhenTheApiReturnsNotFoundDuringAPageNavigation_ShouldThrowCurrentUserAuthorizationException()
{
// Arrange
_httpContext.Request.Headers.Accept = "text/html";
_mockApiHttpClient.GetAsync<GetAuthorizationResponse>(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(Task.FromException<GetAuthorizationResponse>(new ApiException(null, HttpStatusCode.NotFound, "/api/v1/auth/get-authorization?userId=1")));
// Act & Assert
await Assert.ThrowsAsync<CurrentUserAuthorizationException>(() => _sut.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, CancellationToken.None));
}
[Fact]
public async Task HasPermissionAsync_WhenTheApiReturnsAServerErrorDuringAPageNavigation_ShouldReturnFalseAndMarkTheServerUnreachable()
{
// Arrange
_httpContext.Request.Headers.Accept = "text/html";
_mockApiHttpClient.GetAsync<GetAuthorizationResponse>(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(Task.FromException<GetAuthorizationResponse>(new ApiException(null, HttpStatusCode.InternalServerError)));
// Act
bool result = await _sut.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, CancellationToken.None);
// Assert
Assert.False(result);
Assert.True(_httpContext.Items[HttpContextItemKeys.SERVER_UNREACHABLE] is true);
}
}
@@ -0,0 +1,109 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Authorization;
using Lumina.Presentation.Web.Common.Exceptions;
using Lumina.Presentation.Web.Common.Http;
using Lumina.Presentation.Web.Common.Responses.UsersManagement;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using NSubstitute;
using Polly.CircuitBreaker;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Common.Authorization;
/// <summary>
/// Contains unit tests for the <see cref="InitializationHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class InitializationHandlerTests
{
private readonly IApiHttpClient _mockApiHttpClient;
private readonly InitializationHandler _sut;
/// <summary>
/// Initializes a new instance of the <see cref="InitializationHandlerTests"/> class.
/// </summary>
public InitializationHandlerTests()
{
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
_sut = new InitializationHandler(_mockApiHttpClient);
}
[Fact]
public async Task HandleAsync_WhenTheApiIsUnreachableDuringAPageNavigation_ShouldSucceedAndMarkTheServerUnreachable()
{
// Arrange
DefaultHttpContext httpContext = CreateHttpContext();
_mockApiHttpClient.GetAsync<InitializationResponse>(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(Task.FromException<InitializationResponse>(new BrokenCircuitException()));
AuthorizationHandlerContext context = CreateContext(httpContext);
// Act
await _sut.HandleAsync(context);
// Assert
Assert.True(context.HasSucceeded);
Assert.True(httpContext.Items[HttpContextItemKeys.SERVER_UNREACHABLE] is true);
}
[Fact]
public async Task HandleAsync_WhenTheApiReturnsUnauthorizedDuringAPageNavigation_ShouldRethrow()
{
// Arrange
DefaultHttpContext httpContext = CreateHttpContext();
_mockApiHttpClient.GetAsync<InitializationResponse>(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(Task.FromException<InitializationResponse>(new ApiException(null, HttpStatusCode.Unauthorized)));
AuthorizationHandlerContext context = CreateContext(httpContext);
// Act & Assert
await Assert.ThrowsAsync<ApiException>(() => _sut.HandleAsync(context));
}
[Fact]
public async Task HandleAsync_WhenTheApiReturnsAServerErrorDuringAPageNavigation_ShouldSucceedAndMarkTheServerUnreachable()
{
// Arrange
DefaultHttpContext httpContext = CreateHttpContext();
_mockApiHttpClient.GetAsync<InitializationResponse>(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(Task.FromException<InitializationResponse>(new ApiException(null, HttpStatusCode.InternalServerError)));
AuthorizationHandlerContext context = CreateContext(httpContext);
// Act
await _sut.HandleAsync(context);
// Assert
Assert.True(context.HasSucceeded);
Assert.True(httpContext.Items[HttpContextItemKeys.SERVER_UNREACHABLE] is true);
}
/// <summary>
/// Creates a page navigation HTTP context.
/// </summary>
/// <returns>The created HTTP context.</returns>
private static DefaultHttpContext CreateHttpContext()
{
DefaultHttpContext httpContext = new();
httpContext.Request.Headers.Accept = "text/html";
return httpContext;
}
/// <summary>
/// Creates an authorization context that evaluates the initialization requirement.
/// </summary>
/// <param name="httpContext">The HTTP context of the request being authorized.</param>
/// <returns>The created authorization context.</returns>
private static AuthorizationHandlerContext CreateContext(HttpContext httpContext)
{
return new AuthorizationHandlerContext(
[new InitializationRequirement()],
new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString())], "TestAuthentication")),
httpContext);
}
}
@@ -0,0 +1,134 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Authorization;
using Lumina.Presentation.Web.Common.Enums.Authorization;
using Lumina.Presentation.Web.Common.Http;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
using IAuthorizationService = Lumina.Presentation.Web.Common.Authorization.IAuthorizationService;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Common.Authorization;
/// <summary>
/// Contains unit tests for the <see cref="PermissionAuthorizationHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class PermissionAuthorizationHandlerTests
{
private readonly IAuthorizationService _mockAuthorizationService;
private readonly DefaultHttpContext _httpContext;
private readonly PermissionAuthorizationHandler _sut;
/// <summary>
/// Initializes a new instance of the <see cref="PermissionAuthorizationHandlerTests"/> class.
/// </summary>
public PermissionAuthorizationHandlerTests()
{
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_httpContext = new DefaultHttpContext
{
User = new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString())], "TestAuthentication"))
};
IHttpContextAccessor httpContextAccessor = Substitute.For<IHttpContextAccessor>();
httpContextAccessor.HttpContext.Returns(_httpContext);
_sut = new PermissionAuthorizationHandler(_mockAuthorizationService, httpContextAccessor);
}
[Fact]
public async Task HandleAsync_WhenTheUserHoldsTheRequiredPermission_ShouldSucceed()
{
// Arrange
_mockAuthorizationService.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, Arg.Any<CancellationToken>()).Returns(true);
AuthorizationHandlerContext context = CreateContext();
// Act
await _sut.HandleAsync(context);
// Assert
Assert.True(context.HasSucceeded);
}
[Fact]
public async Task HandleAsync_WhenAnAdministratorLacksTheRequiredPermission_ShouldSucceed()
{
// Arrange
// The API lets administrators do what the permission allows even without holding it, so the Web must not deny them.
_mockAuthorizationService.IsInRoleAsync("Admin", Arg.Any<CancellationToken>()).Returns(true);
_mockAuthorizationService.HasPermissionAsync(Arg.Any<AuthorizationPermission>(), Arg.Any<CancellationToken>()).Returns(false);
AuthorizationHandlerContext context = CreateContext();
// Act
await _sut.HandleAsync(context);
// Assert
Assert.True(context.HasSucceeded);
}
[Fact]
public async Task HandleAsync_WhenAUserIsNeitherAnAdministratorNorHoldsTheRequiredPermission_ShouldNotSucceed()
{
// Arrange
_mockAuthorizationService.IsInRoleAsync(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(false);
_mockAuthorizationService.HasPermissionAsync(Arg.Any<AuthorizationPermission>(), Arg.Any<CancellationToken>()).Returns(false);
AuthorizationHandlerContext context = CreateContext();
// Act
await _sut.HandleAsync(context);
// Assert
Assert.False(context.HasSucceeded);
}
[Fact]
public async Task HandleAsync_WhenTheApiWasUnreachableDuringAnAuthenticatedPageNavigation_ShouldSucceed()
{
// Arrange
// The authorization service returns no role or permission when the API is unreachable, and marks the request instead.
_mockAuthorizationService.IsInRoleAsync(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(false);
_mockAuthorizationService.HasPermissionAsync(Arg.Any<AuthorizationPermission>(), Arg.Any<CancellationToken>()).Returns(false);
_httpContext.Items[HttpContextItemKeys.SERVER_UNREACHABLE] = true;
AuthorizationHandlerContext context = CreateContext();
// Act
await _sut.HandleAsync(context);
// Assert
Assert.True(context.HasSucceeded);
}
[Fact]
public async Task HandleAsync_WhenTheApiWasUnreachableDuringAnAnonymousPageNavigation_ShouldNotSucceed()
{
// Arrange
_mockAuthorizationService.IsInRoleAsync(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(false);
_mockAuthorizationService.HasPermissionAsync(Arg.Any<AuthorizationPermission>(), Arg.Any<CancellationToken>()).Returns(false);
_httpContext.User = new ClaimsPrincipal();
_httpContext.Items[HttpContextItemKeys.SERVER_UNREACHABLE] = true;
AuthorizationHandlerContext context = CreateContext();
// Act
await _sut.HandleAsync(context);
// Assert
Assert.False(context.HasSucceeded);
}
/// <summary>
/// Creates an authorization context that evaluates a requirement for the permission to manage media libraries.
/// </summary>
/// <returns>The created authorization context.</returns>
private static AuthorizationHandlerContext CreateContext()
{
// Endpoint routing passes the endpoint, not the HttpContext, as the resource.
return new AuthorizationHandlerContext(
[new PermissionRequirement(AuthorizationPermission.CanCreateLibraries)],
new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString())], "TestAuthentication")),
new Endpoint(null, EndpointMetadataCollection.Empty, "test"));
}
}
@@ -0,0 +1,114 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Authorization;
using Lumina.Presentation.Web.Common.Http;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
using IAuthorizationService = Lumina.Presentation.Web.Common.Authorization.IAuthorizationService;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Common.Authorization;
/// <summary>
/// Contains unit tests for the <see cref="RoleAuthorizationHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RoleAuthorizationHandlerTests
{
private readonly IAuthorizationService _mockAuthorizationService;
private readonly DefaultHttpContext _httpContext;
private readonly RoleAuthorizationHandler _sut;
/// <summary>
/// Initializes a new instance of the <see cref="RoleAuthorizationHandlerTests"/> class.
/// </summary>
public RoleAuthorizationHandlerTests()
{
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_httpContext = new DefaultHttpContext
{
User = new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString())], "TestAuthentication"))
};
IHttpContextAccessor httpContextAccessor = Substitute.For<IHttpContextAccessor>();
httpContextAccessor.HttpContext.Returns(_httpContext);
_sut = new RoleAuthorizationHandler(_mockAuthorizationService, httpContextAccessor);
}
[Fact]
public async Task HandleAsync_WhenTheUserBelongsToTheRequiredRole_ShouldSucceed()
{
// Arrange
_mockAuthorizationService.IsInRoleAsync("Admin", Arg.Any<CancellationToken>()).Returns(true);
AuthorizationHandlerContext context = CreateContext();
// Act
await _sut.HandleAsync(context);
// Assert
Assert.True(context.HasSucceeded);
}
[Fact]
public async Task HandleAsync_WhenTheUserBelongsToNoneOfTheRequiredRoles_ShouldNotSucceed()
{
// Arrange
_mockAuthorizationService.IsInRoleAsync(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(false);
AuthorizationHandlerContext context = CreateContext();
// Act
await _sut.HandleAsync(context);
// Assert
Assert.False(context.HasSucceeded);
}
[Fact]
public async Task HandleAsync_WhenTheApiWasUnreachableDuringAnAuthenticatedPageNavigation_ShouldSucceed()
{
// Arrange
// The authorization service returns no role when the API is unreachable, and marks the request instead.
_mockAuthorizationService.IsInRoleAsync(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(false);
_httpContext.Items[HttpContextItemKeys.SERVER_UNREACHABLE] = true;
AuthorizationHandlerContext context = CreateContext();
// Act
await _sut.HandleAsync(context);
// Assert
Assert.True(context.HasSucceeded);
}
[Fact]
public async Task HandleAsync_WhenTheApiWasUnreachableDuringAnAnonymousPageNavigation_ShouldNotSucceed()
{
// Arrange
_mockAuthorizationService.IsInRoleAsync(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(false);
_httpContext.User = new ClaimsPrincipal();
_httpContext.Items[HttpContextItemKeys.SERVER_UNREACHABLE] = true;
AuthorizationHandlerContext context = CreateContext();
// Act
await _sut.HandleAsync(context);
// Assert
Assert.False(context.HasSucceeded);
}
/// <summary>
/// Creates an authorization context that evaluates a requirement for the administrator role.
/// </summary>
/// <returns>The created authorization context.</returns>
private static AuthorizationHandlerContext CreateContext()
{
// Endpoint routing passes the endpoint, not the HttpContext, as the resource.
return new AuthorizationHandlerContext(
[new RoleRequirement("Admin")],
new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString())], "TestAuthentication")),
new Endpoint(null, EndpointMetadataCollection.Empty, "test"));
}
}
@@ -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);
}
}
@@ -0,0 +1,180 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Http;
using Microsoft.AspNetCore.Http;
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Common.Http;
/// <summary>
/// Contains unit tests for the <see cref="ApiStreamProxy"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ApiStreamProxyTests
{
/// <summary>
/// Initializes a new instance of the <see cref="ApiStreamProxyTests"/> class.
/// </summary>
public ApiStreamProxyTests()
{
}
[Fact]
public async Task WriteAsync_WhenCalled_ShouldCopyTheStatusCodeAndTheContentHeaders()
{
// Arrange
byte[] contentBytes = CreateBytes(96);
using HttpResponseMessage apiResponse = CreateResponse(HttpStatusCode.PartialContent, contentBytes);
apiResponse.Content.Headers.ContentType = new MediaTypeHeaderValue("audio/mp4");
apiResponse.Headers.AcceptRanges.Add("bytes");
apiResponse.Headers.ETag = new EntityTagHeaderValue("\"etag-value\"");
DateTimeOffset lastModified = new(2026, 1, 2, 3, 4, 5, TimeSpan.Zero);
apiResponse.Content.Headers.LastModified = lastModified;
apiResponse.Content.Headers.ContentRange = new ContentRangeHeaderValue(10, 105, 1024);
apiResponse.Headers.TryAddWithoutValidation(ApiStreamResult.SEGMENT_COUNT_HEADER_NAME, "9");
apiResponse.Headers.TryAddWithoutValidation(ApiStreamResult.SEGMENT_START_SECONDS_HEADER_NAME, "6.5");
apiResponse.Headers.TryAddWithoutValidation(ApiStreamResult.TRACK_DURATION_SECONDS_HEADER_NAME, "300");
await using ApiStreamResult streamResult = await ApiStreamResult.CreateAsync(apiResponse, CancellationToken.None);
DefaultHttpContext httpContext = CreateHttpContext();
// Act
await ApiStreamProxy.WriteAsync(httpContext.Response, streamResult, CancellationToken.None);
// Assert
Assert.Equal(StatusCodes.Status206PartialContent, httpContext.Response.StatusCode);
Assert.Equal("audio/mp4", httpContext.Response.ContentType);
Assert.Equal(contentBytes.Length, httpContext.Response.ContentLength);
Assert.Equal("bytes 10-105/1024", httpContext.Response.Headers["Content-Range"].ToString());
Assert.Equal("bytes", httpContext.Response.Headers["Accept-Ranges"].ToString());
Assert.Equal("\"etag-value\"", httpContext.Response.Headers["ETag"].ToString());
Assert.Equal(lastModified.ToString("R"), httpContext.Response.Headers["Last-Modified"].ToString());
Assert.Equal("9", httpContext.Response.Headers[ApiStreamResult.SEGMENT_COUNT_HEADER_NAME].ToString());
Assert.Equal("6.5", httpContext.Response.Headers[ApiStreamResult.SEGMENT_START_SECONDS_HEADER_NAME].ToString());
Assert.Equal("300", httpContext.Response.Headers[ApiStreamResult.TRACK_DURATION_SECONDS_HEADER_NAME].ToString());
Assert.Equal("Cookie", httpContext.Response.Headers["Vary"].ToString());
}
[Fact]
public async Task WriteAsync_WhenOptionalHeadersAreAbsent_ShouldNotAddThem()
{
// Arrange
using HttpResponseMessage apiResponse = CreateResponse(HttpStatusCode.OK, CreateBytes(16));
await using ApiStreamResult streamResult = await ApiStreamResult.CreateAsync(apiResponse, CancellationToken.None);
DefaultHttpContext httpContext = CreateHttpContext();
// Act
await ApiStreamProxy.WriteAsync(httpContext.Response, streamResult, CancellationToken.None);
// Assert
Assert.False(httpContext.Response.Headers.ContainsKey("Content-Range"));
Assert.False(httpContext.Response.Headers.ContainsKey("Accept-Ranges"));
Assert.False(httpContext.Response.Headers.ContainsKey("ETag"));
Assert.False(httpContext.Response.Headers.ContainsKey("Last-Modified"));
Assert.False(httpContext.Response.Headers.ContainsKey(ApiStreamResult.SEGMENT_COUNT_HEADER_NAME));
Assert.False(httpContext.Response.Headers.ContainsKey(ApiStreamResult.SEGMENT_START_SECONDS_HEADER_NAME));
Assert.False(httpContext.Response.Headers.ContainsKey(ApiStreamResult.TRACK_DURATION_SECONDS_HEADER_NAME));
}
[Theory]
[InlineData("public, max-age=60", new[] { "private", "max-age=60" })] // The public instruction is dropped and the max age is preserved.
[InlineData("no-store", new[] { "private", "no-store" })] // The no store instruction is preserved and privacy is added.
[InlineData(null, new[] { "private" })] // An absent API instruction becomes a private instruction.
public async Task WriteAsync_WhenApiDeclaresCaching_ShouldAlwaysProduceAPrivateInstruction(string? apiCacheControl, string[] expectedFragments)
{
// Arrange
using HttpResponseMessage apiResponse = CreateResponse(HttpStatusCode.OK, CreateBytes(16));
if (apiCacheControl is not null)
apiResponse.Headers.CacheControl = CacheControlHeaderValue.Parse(apiCacheControl);
await using ApiStreamResult streamResult = await ApiStreamResult.CreateAsync(apiResponse, CancellationToken.None);
DefaultHttpContext httpContext = CreateHttpContext();
// Act
await ApiStreamProxy.WriteAsync(httpContext.Response, streamResult, CancellationToken.None);
// Assert
string cacheControl = httpContext.Response.Headers["Cache-Control"].ToString();
Assert.DoesNotContain("public", cacheControl, StringComparison.OrdinalIgnoreCase);
foreach (string fragment in expectedFragments)
Assert.Contains(fragment, cacheControl, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task WriteAsync_WhenCalled_ShouldCopyTheBodyExactly()
{
// Arrange
byte[] contentBytes = CreateBytes(2048);
using HttpResponseMessage apiResponse = CreateResponse(HttpStatusCode.OK, contentBytes);
await using ApiStreamResult streamResult = await ApiStreamResult.CreateAsync(apiResponse, CancellationToken.None);
DefaultHttpContext httpContext = CreateHttpContext();
// Act
await ApiStreamProxy.WriteAsync(httpContext.Response, streamResult, CancellationToken.None);
// Assert
httpContext.Response.Body.Position = 0;
using MemoryStream writtenBody = new();
httpContext.Response.Body.CopyTo(writtenBody);
Assert.Equal(contentBytes, writtenBody.ToArray());
}
[Fact]
public async Task WriteAsync_WhenCancellationIsRequested_ShouldCancelTheCopy()
{
// Arrange
using HttpResponseMessage apiResponse = CreateResponse(HttpStatusCode.OK, CreateBytes(2048));
await using ApiStreamResult streamResult = await ApiStreamResult.CreateAsync(apiResponse, CancellationToken.None);
DefaultHttpContext httpContext = CreateHttpContext();
using CancellationTokenSource cancellationTokenSource = new();
cancellationTokenSource.Cancel();
// Act
Task operationTask = ApiStreamProxy.WriteAsync(httpContext.Response, streamResult, cancellationTokenSource.Token);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
}
/// <summary>
/// Creates a <see cref="DefaultHttpContext"/> with a writable response body.
/// </summary>
/// <returns>The configured HTTP context.</returns>
private static DefaultHttpContext CreateHttpContext()
{
DefaultHttpContext httpContext = new();
httpContext.Response.Body = new MemoryStream();
return httpContext;
}
/// <summary>
/// Creates a streamed API response with a status code and a body.
/// </summary>
/// <param name="statusCode">The status code of the response.</param>
/// <param name="contentBytes">The bytes of the content of the response.</param>
/// <returns>The created HTTP response.</returns>
private static HttpResponseMessage CreateResponse(HttpStatusCode statusCode, byte[] contentBytes)
{
return new HttpResponseMessage(statusCode)
{
Content = new ByteArrayContent(contentBytes)
};
}
/// <summary>
/// Creates a deterministic byte array that stands in for streamed content.
/// </summary>
/// <param name="length">The number of bytes to create.</param>
/// <returns>The created bytes.</returns>
private static byte[] CreateBytes(int length)
{
return [.. Enumerable.Range(0, length).Select(index => (byte)(index % 256))];
}
}
@@ -0,0 +1,74 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Localization;
using Microsoft.AspNetCore.Mvc.Localization;
using Microsoft.Extensions.Localization;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Common.Localization;
/// <summary>
/// Contains unit tests for the <see cref="CoreHtmlLocalizerFactory"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class CoreHtmlLocalizerFactoryTests
{
private readonly IStringLocalizerFactory _mockStringLocalizerFactory;
private readonly CoreHtmlLocalizerFactory _sut;
/// <summary>
/// Initializes a new instance of the <see cref="CoreHtmlLocalizerFactoryTests"/> class.
/// </summary>
public CoreHtmlLocalizerFactoryTests()
{
_mockStringLocalizerFactory = Substitute.For<IStringLocalizerFactory>();
_mockStringLocalizerFactory.Create(Arg.Any<string>(), Arg.Any<string>()).Returns(Substitute.For<IStringLocalizer>());
_sut = new CoreHtmlLocalizerFactory(_mockStringLocalizerFactory);
}
[Fact]
public void Create_WhenBaseNameStartsWithLocationCorePrefix_ShouldStripCoreSegment()
{
// Act
IHtmlLocalizer localizer = _sut.Create("Lumina.Presentation.Web.Core.Views.Auth.Login", "Lumina.Presentation.Web");
// Assert
Assert.NotNull(localizer);
_mockStringLocalizerFactory.Received(1).Create("Lumina.Presentation.Web.Views.Auth.Login", "Lumina.Presentation.Web");
}
[Fact]
public void Create_WhenBaseNameDoesNotStartWithLocationCorePrefix_ShouldKeepBaseNameUnchanged()
{
// Act
IHtmlLocalizer localizer = _sut.Create("Lumina.Presentation.Web.Views.Shared.Layout", "Lumina.Presentation.Web");
// Assert
Assert.NotNull(localizer);
_mockStringLocalizerFactory.Received(1).Create("Lumina.Presentation.Web.Views.Shared.Layout", "Lumina.Presentation.Web");
}
[Fact]
public void Create_WhenResourceSourceTypeProvided_ShouldCreateLocalizerForType()
{
// Arrange
_mockStringLocalizerFactory.Create(Arg.Any<Type>()).Returns(Substitute.For<IStringLocalizer>());
// Act
IHtmlLocalizer localizer = _sut.Create(typeof(TestLocalizationResource));
// Assert
Assert.NotNull(localizer);
_mockStringLocalizerFactory.Received(1).Create(typeof(TestLocalizationResource));
}
/// <summary>
/// Marker type used for the resource source based localizer creation test.
/// </summary>
[ExcludeFromCodeCoverage]
private sealed class TestLocalizationResource
{
}
}
@@ -0,0 +1,164 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Http;
using Lumina.Presentation.Web.Common.Middlewares;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using System;
using System.Collections.Generic;
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="CacheControlHeaderMiddleware"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class CacheControlHeaderMiddlewareTests
{
[Fact]
public async Task InvokeAsync_WhenTheEndpointStoredACacheControlValue_ShouldRestoreItAfterLaterCallbacksRun()
{
// Arrange
DefaultHttpContext context = new();
TestHttpResponseFeature responseFeature = new();
context.Features.Set<IHttpResponseFeature>(responseFeature);
context.Items[HttpContextItemKeys.CACHE_CONTROL] = "private, no-store";
CacheControlHeaderMiddleware sut = new(nextContext =>
{
// The session middleware registers its cache header write after this middleware, so it runs first when the response starts.
nextContext.Response.OnStarting(() =>
{
nextContext.Response.Headers.CacheControl = "no-cache,no-store";
return Task.CompletedTask;
});
return Task.CompletedTask;
});
// Act
await sut.InvokeAsync(context);
await responseFeature.StartAsync();
// Assert
Assert.Equal("private, no-store", context.Response.Headers.CacheControl.ToString());
}
[Fact]
public async Task InvokeAsync_WhenNoCacheControlValueWasStored_ShouldLeaveTheHeaderWrittenByLaterCallbacks()
{
// Arrange
DefaultHttpContext context = new();
TestHttpResponseFeature responseFeature = new();
context.Features.Set<IHttpResponseFeature>(responseFeature);
CacheControlHeaderMiddleware sut = new(nextContext =>
{
nextContext.Response.OnStarting(() =>
{
nextContext.Response.Headers.CacheControl = "no-cache,no-store";
return Task.CompletedTask;
});
return Task.CompletedTask;
});
// Act
await sut.InvokeAsync(context);
await responseFeature.StartAsync();
// Assert
Assert.Equal("no-cache,no-store", context.Response.Headers.CacheControl.ToString());
}
[Fact]
public async Task InvokeAsync_WhenTheStoredValueIsEmpty_ShouldLeaveTheHeaderWrittenByLaterCallbacks()
{
// Arrange
DefaultHttpContext context = new();
TestHttpResponseFeature responseFeature = new();
context.Features.Set<IHttpResponseFeature>(responseFeature);
context.Items[HttpContextItemKeys.CACHE_CONTROL] = string.Empty;
CacheControlHeaderMiddleware sut = new(nextContext =>
{
nextContext.Response.OnStarting(() =>
{
nextContext.Response.Headers.CacheControl = "no-cache,no-store";
return Task.CompletedTask;
});
return Task.CompletedTask;
});
// Act
await sut.InvokeAsync(context);
await responseFeature.StartAsync();
// Assert
Assert.Equal("no-cache,no-store", context.Response.Headers.CacheControl.ToString());
}
/// <summary>
/// Minimal response feature that stores the response-start callbacks and invokes them in reverse registration order, like the server does.
/// </summary>
[ExcludeFromCodeCoverage]
private sealed class TestHttpResponseFeature : IHttpResponseFeature
{
private readonly List<(Func<object, Task> Callback, object State)> _onStartingCallbacks = [];
/// <summary>
/// Gets or sets the 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 headers of the response.
/// </summary>
public IHeaderDictionary Headers { get; set; } = new HeaderDictionary();
/// <summary>
/// Gets or sets the body of the response.
/// </summary>
public Stream Body { get; set; } = new MemoryStream();
/// <summary>
/// Gets a value indicating whether the response has started.
/// </summary>
public bool HasStarted { get; private set; }
/// <summary>
/// Registers a callback to invoke when the response starts.
/// </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)
{
_onStartingCallbacks.Add((callback, state));
}
/// <summary>
/// Registers a callback to invoke when the response completes.
/// </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)
{
}
/// <summary>
/// Starts the response and invokes the registered callbacks in reverse registration order.
/// </summary>
/// <returns>A task representing the asynchronous operation.</returns>
public async Task StartAsync()
{
if (HasStarted)
return;
HasStarted = true;
for (int index = _onStartingCallbacks.Count - 1; index >= 0; index--)
await _onStartingCallbacks[index].Callback(_onStartingCallbacks[index].State);
}
}
}
@@ -0,0 +1,530 @@
#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>>();
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(true);
_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_WhenNextThrowsNonApiExceptionAndApiRequest_ShouldLogErrorAndWriteFailureJson()
{
// Arrange
DefaultHttpContext httpContext = CreateHttpContext(isApiRequest: true);
_nextDelegate = _ => throw new InvalidOperationException("Unexpected failure");
// Act
await _sut.InvokeAsync(httpContext);
// Assert
Assert.Contains("application/json", httpContext.Response.ContentType);
string body = await ReadResponseBodyAsync(httpContext);
using JsonDocument jsonDocument = JsonDocument.Parse(body);
Assert.False(jsonDocument.RootElement.GetProperty("success").GetBoolean());
// An ordinary bug is not an unreachable server, so the client must not switch to the outage path for it.
Assert.False(jsonDocument.RootElement.GetProperty("serverUnreachable").GetBoolean());
Assert.Equal("localized:InternalServerError", 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_WhenLoggingIsDisabledAndNextThrowsNonApiExceptionAndApiRequest_ShouldNotLogError()
{
// Arrange
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(false);
DefaultHttpContext httpContext = CreateHttpContext(isApiRequest: true);
_nextDelegate = _ => throw new InvalidOperationException("Unexpected failure");
// Act
await _sut.InvokeAsync(httpContext);
// Assert
Assert.Contains("application/json", httpContext.Response.ContentType);
_mockLogger.DidNotReceive().Log(
LogLevel.Error,
Arg.Any<EventId>(),
Arg.Any<object>(),
Arg.Any<Exception?>(),
Arg.Any<Func<object, Exception?, string>>());
}
[Fact]
public async Task InvokeAsync_WhenNextThrowsNonApiExceptionAndPageRequest_ShouldWriteHtmlErrorPage()
{
// Arrange
DefaultHttpContext httpContext = CreateHttpContext(culture: "de-DE");
httpContext.Request.Headers.Accept = "text/html";
_nextDelegate = _ => throw new InvalidOperationException("Unexpected failure");
// Act
await _sut.InvokeAsync(httpContext);
// Assert
Assert.Equal(StatusCodes.Status500InternalServerError, httpContext.Response.StatusCode);
Assert.Contains("text/html", httpContext.Response.ContentType);
Assert.Contains("localized:InternalServerError", await ReadResponseBodyAsync(httpContext));
_mockLogger.Received(1).Log(
LogLevel.Error,
Arg.Any<EventId>(),
Arg.Any<object>(),
Arg.Is<Exception>(exception => exception is InvalidOperationException && exception.Message == "Unexpected failure"),
Arg.Any<Func<object, Exception?, string>>());
}
[Fact]
public async Task InvokeAsync_WhenNextThrowsNonApiExceptionAndRequestStatesNoPreference_ShouldWriteFailureJson()
{
// Arrange
// A caller that sends no Accept header is not proven to be a browser, so it keeps the historical JSON envelope.
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.False(jsonDocument.RootElement.GetProperty("serverUnreachable").GetBoolean());
Assert.Equal("localized:InternalServerError", jsonDocument.RootElement.GetProperty("errorMessage").GetString());
}
[Fact]
public async Task InvokeAsync_WhenNextThrowsNonApiExceptionAndRawRequest_ShouldWriteStatusCodeWithoutBody()
{
// Arrange
DefaultHttpContext httpContext = CreateHttpContext();
httpContext.Request.Headers.Accept = "audio/mpeg";
_nextDelegate = _ => throw new InvalidOperationException("Unexpected failure");
// Act
await _sut.InvokeAsync(httpContext);
// Assert
Assert.Equal(StatusCodes.Status500InternalServerError, httpContext.Response.StatusCode);
Assert.Equal(0, httpContext.Response.Body.Length);
}
[Fact]
public async Task InvokeAsync_WhenApiExceptionUnauthorizedAndApiRequest_ShouldSignOutAndWriteUnauthorizedJson()
{
// 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 CurrentUserAuthorizationException(_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 CurrentUserAuthorizationException(_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_WhenApiExceptionNotFoundWithCraftedAuthorizationPathAndAuthenticatedPageRequest_ShouldNotSignOut()
{
// Arrange
DefaultHttpContext httpContext = CreateHttpContext(isApiRequest: false, culture: "en-us", user: CreateAuthenticatedUser(), requestServices: CreateServiceProvider());
httpContext.Request.Headers.Accept = "text/html";
httpContext.Request.Path = "/en-us/theme-assets/test-theme/auth/get-authorization";
_nextDelegate = _ => throw new ApiException(_problemDetailsDtoFixture.Create(), HttpStatusCode.NotFound, "/api/v1/themes/test-theme/assets/auth/get-authorization");
// Act
await _sut.InvokeAsync(httpContext);
// Assert
Assert.Equal(StatusCodes.Status302Found, httpContext.Response.StatusCode);
Assert.Equal("/en-us/not-found", httpContext.Response.Headers.Location.ToString());
await _mockAuthenticationService.DidNotReceive().SignOutAsync(Arg.Any<HttpContext>(), Arg.Any<string?>(), 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 = _problemDetailsDtoFixture.Create(title: "General.Failure", status: 400, includeType: false, includeDetail: false);
_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 body = await ReadResponseBodyAsync(httpContext);
using JsonDocument jsonDocument = JsonDocument.Parse(body);
string errorMessage = jsonDocument.RootElement.GetProperty("errorMessage").GetString() ?? string.Empty;
Assert.Contains("An error occurred.", errorMessage);
Assert.Contains("localized:InternalServerError", errorMessage);
Assert.True(jsonDocument.RootElement.GetProperty("serverUnreachable").GetBoolean());
}
[Fact]
public async Task InvokeAsync_WhenApiExceptionHasNoProblemDetailsAndPageRequest_ShouldWriteHtmlErrorPage()
{
// Arrange
DefaultHttpContext httpContext = CreateHttpContext(culture: "en-US");
_nextDelegate = _ => throw new ApiException(null, HttpStatusCode.InternalServerError, "/api/v1/libraries/1");
// Act
await _sut.InvokeAsync(httpContext);
// Assert
Assert.Equal(StatusCodes.Status500InternalServerError, httpContext.Response.StatusCode);
Assert.Contains("text/html", httpContext.Response.ContentType);
Assert.Contains("localized:InternalServerError", await ReadResponseBodyAsync(httpContext));
}
[Fact]
public async Task InvokeAsync_WhenApiExceptionHasClientErrorAndPageRequest_ShouldWriteHtmlErrorPageWithTheRealStatusAndLocalizedMessage()
{
// Arrange
DefaultHttpContext httpContext = CreateHttpContext(culture: "en-US");
ProblemDetailsDto problemDetails = _problemDetailsDtoFixture.Create(detail: "Validation.Failed", title: "General.Validation", status: 422);
_nextDelegate = _ => throw new ApiException(problemDetails, (HttpStatusCode)422);
// Act
await _sut.InvokeAsync(httpContext);
// Assert
Assert.Equal(422, httpContext.Response.StatusCode);
Assert.Contains("text/html", httpContext.Response.ContentType);
Assert.Contains("localized:Validation.Failed", await ReadResponseBodyAsync(httpContext));
}
/// <summary>
/// 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)!;
}
}
@@ -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)
{
}
}
}
@@ -0,0 +1,57 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Playback;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Common.Playback;
/// <summary>
/// Contains unit tests for the <see cref="PlaybackDeliveryId"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class PlaybackDeliveryIdTests
{
[Theory]
[InlineData("0123456789abcdef0123456789abcdef")] // A lowercase hexadecimal handle.
[InlineData("ffffffffffffffffffffffffffffffff")] // An all lowercase hexadecimal handle.
[InlineData("00000000000000000000000000000000")] // An all zero handle.
[InlineData("8f14e45fceea167a5a36dedd4bea2543")] // A random lowercase hexadecimal handle.
public void IsValid_WhenValueIsThirtyTwoLowercaseHexadecimalCharacters_ShouldReturnTrue(string value)
{
// Act
bool result = PlaybackDeliveryId.IsValid(value);
// Assert
Assert.True(result);
}
[Theory]
[InlineData(null)] // An absent handle is not valid.
[InlineData("")] // An empty handle is not valid.
[InlineData(" ")] // A whitespace only handle is not valid.
[InlineData("0123456789abcdef0123456789abcde")] // A handle with 31 characters is too short.
[InlineData("0123456789abcdef0123456789abcdef0")] // A handle with 33 characters is too long.
[InlineData("0123456789ABCDEF0123456789ABCDEF")] // An uppercase handle is not accepted.
[InlineData("01234567-89ab-cdef-0123-456789abcdef")] // A dashed GUID is not accepted.
[InlineData("0123456789abcdef0123456789abcdeg")] // A non hexadecimal handle is not accepted.
[InlineData("0123456789abcdef0123456789abcde ")] // A handle with a trailing space is not accepted.
public void IsValid_WhenValueDoesNotMatchTheHandleFormat_ShouldReturnFalse(string? value)
{
// Act
bool result = PlaybackDeliveryId.IsValid(value);
// Assert
Assert.False(result);
}
[Fact]
public void CharacterCount_ShouldBeThirtyTwo()
{
// Act
int characterCount = PlaybackDeliveryId.CHARACTER_COUNT;
// Assert
Assert.Equal(32, characterCount);
}
}
@@ -0,0 +1,90 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.DTO.Configuration;
using Lumina.Presentation.Web.Common.Security;
using Lumina.Presentation.Web.Fixtures.Common.DTO.Configuration;
using Microsoft.Extensions.Options;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Common.Security;
/// <summary>
/// Contains unit tests for the <see cref="CryptographyService"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class CryptographyServiceTests
{
private const string TEST_ENCRYPTION_KEY = "FLYO0QRo6u2VzoFOgNkkEwYNGtqhJ3QGZd7iAHNEJeM=";
private readonly EncryptionSettingsDtoFixture _encryptionSettingsDtoFixture = new();
private readonly CryptographyService _sut;
/// <summary>
/// Initializes a new instance of the <see cref="CryptographyServiceTests"/> class.
/// </summary>
public CryptographyServiceTests()
{
EncryptionSettingsDto settings = _encryptionSettingsDtoFixture.Create(secretKey: TEST_ENCRYPTION_KEY);
_sut = new CryptographyService(Options.Create(settings));
}
[Fact]
public void Encrypt_WhenCalled_ShouldReturnCiphertextThatDecryptsToPlaintext()
{
// Arrange
const string PLAINTEXT = "sensitive-data";
// Act
string ciphertext = _sut.Encrypt(PLAINTEXT);
// Assert
Assert.NotEqual(PLAINTEXT, ciphertext);
Assert.Equal(PLAINTEXT, _sut.Decrypt(ciphertext));
}
[Fact]
public void Encrypt_WhenCalledTwice_ShouldReturnDifferentCiphertexts()
{
// Arrange
const string PLAINTEXT = "sensitive-data";
// Act
string firstCiphertext = _sut.Encrypt(PLAINTEXT);
string secondCiphertext = _sut.Encrypt(PLAINTEXT);
// Assert
Assert.NotEqual(firstCiphertext, secondCiphertext);
}
[Theory]
[InlineData(null)]
[InlineData("")]
public void Encrypt_WhenPlaintextIsNullOrEmpty_ShouldThrowArgumentException(string? plaintext)
{
// Act
ArgumentException exception = Assert.Throws<ArgumentException>(() => _sut.Encrypt(plaintext!));
// Assert
Assert.Equal("plaintext", exception.ParamName);
}
[Fact]
public void Decrypt_WhenCiphertextIsNotValidBase64_ShouldThrowFormatException()
{
// Act
FormatException exception = Assert.Throws<FormatException>(() => _sut.Decrypt("not-valid-base64!!!"));
// Assert
Assert.Contains("Base-64", exception.Message);
}
[Fact]
public void Decrypt_WhenCiphertextIsTooShort_ShouldThrowArgumentException()
{
// Act
ArgumentException exception = Assert.Throws<ArgumentException>(() => _sut.Decrypt(Convert.ToBase64String([1, 2, 3])));
// Assert
Assert.Equal("Invalid ciphertext", exception.Message);
}
}
@@ -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")
};
}
}
@@ -0,0 +1,157 @@
#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="CachedThemeHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class CachedThemeHandlerTests
{
private readonly HybridCache _hybridCache;
private readonly ThemeCachePreferenceService _themeCachePreferenceService;
/// <summary>
/// Initializes a new instance of the <see cref="CachedThemeHandlerTests"/> class.
/// </summary>
public CachedThemeHandlerTests()
{
ServiceCollection services = new();
services.AddHybridCache();
_hybridCache = services.BuildServiceProvider().GetRequiredService<HybridCache>();
_themeCachePreferenceService = new ThemeCachePreferenceService(_hybridCache);
}
[Fact]
public async Task SendAsync_WhenThemeGetRequestIsServedTwice_ShouldCallInnerHandlerOnlyOnce()
{
// Arrange
TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.OK, """{"themeId":"editorial-paper"}"""));
HttpClient client = CreateClient(messageHandler);
// Act
await client.GetAsync("http://localhost:5214/api/v1/themes/editorial-paper/templates/shared/layout", CancellationToken.None);
await client.GetAsync("http://localhost:5214/api/v1/themes/editorial-paper/templates/shared/layout", CancellationToken.None);
// Assert
Assert.Single(messageHandler.Requests);
}
[Fact]
public async Task SendAsync_WhenNonThemeGetRequestIsServedTwice_ShouldCallInnerHandlerTwice()
{
// Arrange
TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.OK, """[{"title":"Library One"}]"""));
HttpClient client = CreateClient(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_WhenThemeMutationIsPerformed_ShouldInvalidateCachedThemeResponses()
{
// Arrange
TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.OK, """{"themeId":"editorial-paper"}"""));
HttpClient client = CreateClient(messageHandler);
// Act
await client.GetAsync("http://localhost:5214/api/v1/themes/current", CancellationToken.None);
await client.PutAsync("http://localhost:5214/api/v1/themes/current", new StringContent("""{"themeId":"lumina-default"}""", Encoding.UTF8, "application/json"), CancellationToken.None);
await client.GetAsync("http://localhost:5214/api/v1/themes/current", CancellationToken.None);
// Assert
Assert.Equal(3, messageHandler.Requests.Count);
}
[Fact]
public async Task SendAsync_WhenThemeGetRequestFails_ShouldNotRetainTheFailedResponse()
{
// Arrange
TestApiHttpMessageHandler messageHandler = new(_ => new HttpResponseMessage(HttpStatusCode.InternalServerError));
HttpClient client = CreateClient(messageHandler);
// Act
await client.GetAsync("http://localhost:5214/api/v1/themes/current", CancellationToken.None);
await client.GetAsync("http://localhost:5214/api/v1/themes/current", CancellationToken.None);
// Assert
Assert.Equal(2, messageHandler.Requests.Count);
}
[Fact]
public async Task SendAsync_WhenThemeGetResponseExceedsMaxCacheableSize_ShouldNotCacheIt()
{
// Arrange
byte[] largeContent = new byte[600 * 1024];
TestApiHttpMessageHandler messageHandler = new(_ => new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(largeContent) });
HttpClient client = CreateClient(messageHandler);
// Act
await client.GetAsync("http://localhost:5214/api/v1/themes/editorial-paper/assets/preview.png", CancellationToken.None);
await client.GetAsync("http://localhost:5214/api/v1/themes/editorial-paper/assets/preview.png", CancellationToken.None);
// Assert
Assert.Equal(2, messageHandler.Requests.Count);
}
[Fact]
public async Task SendAsync_WhenUserDisablesThemeCaching_ShouldCallInnerHandlerForEveryRequest()
{
// Arrange
Guid userId = Guid.NewGuid();
TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.OK, """{"themeId":"editorial-paper"}"""));
HttpClient client = CreateClient(messageHandler, userId: userId);
await _themeCachePreferenceService.SetAsync(userId, isEnabled: false, CancellationToken.None);
// Act
await client.GetAsync("http://localhost:5214/api/v1/themes/current", CancellationToken.None);
await client.GetAsync("http://localhost:5214/api/v1/themes/current", CancellationToken.None);
// Assert
Assert.Equal(2, messageHandler.Requests.Count);
}
private HttpClient CreateClient(TestApiHttpMessageHandler messageHandler, Guid? userId = null)
{
IHttpContextAccessor httpContextAccessor = Substitute.For<IHttpContextAccessor>();
if (userId is not null)
{
DefaultHttpContext httpContext = new();
httpContext.User = new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, userId.Value.ToString())], "TestAuthentication"));
httpContextAccessor.HttpContext.Returns(httpContext);
}
CachedThemeHandler themeHandler = new(_hybridCache, httpContextAccessor, _themeCachePreferenceService)
{
InnerHandler = messageHandler
};
return new HttpClient(themeHandler);
}
private static HttpResponseMessage CreateJsonResponse(HttpStatusCode statusCode, string json)
{
return new HttpResponseMessage(statusCode)
{
Content = new StringContent(json, Encoding.UTF8, "application/json")
};
}
}
@@ -0,0 +1,49 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Services;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Common.Services;
/// <summary>
/// Contains unit tests for the <see cref="ScriptIdentifierHelper"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ScriptIdentifierHelperTests
{
[Fact]
public void GenerateScriptId_WhenCalled_ShouldReturnScriptPrefixedIdentifier()
{
// Act
string scriptId = ScriptIdentifierHelper.GenerateScriptId();
// Assert
Assert.StartsWith("script_", scriptId);
Assert.True(Guid.TryParse(scriptId.AsSpan("script_".Length), out _));
}
[Fact]
public void GenerateScriptId_WhenCalledTwice_ShouldReturnDistinctIdentifiers()
{
// Act
string firstScriptId = ScriptIdentifierHelper.GenerateScriptId();
string secondScriptId = ScriptIdentifierHelper.GenerateScriptId();
// Assert
Assert.NotEqual(firstScriptId, secondScriptId);
}
[Fact]
public void ClearIdentifier_WhenCalledWithGeneratedIdentifier_ShouldNotThrow()
{
// Arrange
string scriptId = ScriptIdentifierHelper.GenerateScriptId();
// Act
ScriptIdentifierHelper.ClearIdentifier(scriptId);
// Assert
Assert.NotNull(scriptId);
}
}
@@ -0,0 +1,104 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Services;
using Microsoft.Extensions.Caching.Hybrid;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Common.Services;
/// <summary>
/// Contains unit tests for the <see cref="ThemeCachePreferenceService"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ThemeCachePreferenceServiceTests
{
private readonly HybridCache _hybridCache;
private readonly ThemeCachePreferenceService _sut;
/// <summary>
/// Initializes a new instance of the <see cref="ThemeCachePreferenceService"/> class.
/// </summary>
public ThemeCachePreferenceServiceTests()
{
ServiceCollection services = new();
services.AddHybridCache();
_hybridCache = services.BuildServiceProvider().GetRequiredService<HybridCache>();
_sut = new ThemeCachePreferenceService(_hybridCache);
}
[Fact]
public async Task GetAsync_WhenNoPreferenceStored_ShouldReturnDefaultValue()
{
// Arrange
Guid userId = Guid.NewGuid();
// Act
bool result = await _sut.GetAsync(userId, isCachingEnabledByDefault: true, CancellationToken.None);
// Assert
Assert.True(result);
}
[Fact]
public async Task GetAsync_WhenNoPreferenceStoredAndDefaultIsFalse_ShouldReturnFalse()
{
// Arrange
Guid userId = Guid.NewGuid();
// Act
bool result = await _sut.GetAsync(userId, isCachingEnabledByDefault: false, CancellationToken.None);
// Assert
Assert.False(result);
}
[Fact]
public async Task SetAsync_WhenPreferenceStored_ShouldReturnTheStoredValue()
{
// Arrange
Guid userId = Guid.NewGuid();
// Act
await _sut.SetAsync(userId, isEnabled: true, CancellationToken.None);
bool result = await _sut.GetAsync(userId, isCachingEnabledByDefault: false, CancellationToken.None);
// Assert
Assert.True(result);
}
[Fact]
public async Task SetAsync_WhenPreferenceOverwritten_ShouldReturnTheNewValue()
{
// Arrange
Guid userId = Guid.NewGuid();
// Act
await _sut.SetAsync(userId, isEnabled: true, CancellationToken.None);
await _sut.SetAsync(userId, isEnabled: false, CancellationToken.None);
bool result = await _sut.GetAsync(userId, isCachingEnabledByDefault: true, CancellationToken.None);
// Assert
Assert.False(result);
}
[Fact]
public async Task SetAsync_WhenStoredForOneUser_ShouldNotAffectAnotherUser()
{
// Arrange
Guid firstUserId = Guid.NewGuid();
Guid secondUserId = Guid.NewGuid();
// Act
await _sut.SetAsync(firstUserId, isEnabled: true, CancellationToken.None);
bool firstUserResult = await _sut.GetAsync(firstUserId, isCachingEnabledByDefault: false, CancellationToken.None);
bool secondUserResult = await _sut.GetAsync(secondUserId, isCachingEnabledByDefault: false, CancellationToken.None);
// Assert
Assert.True(firstUserResult);
Assert.False(secondUserResult);
}
}
@@ -0,0 +1,293 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Common.Services;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Microsoft.AspNetCore.Http;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Common.Services;
/// <summary>
/// Contains unit tests for the <see cref="UrlService"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UrlServiceTests
{
private readonly IHttpContextAccessor _mockHttpContextAccessor;
private readonly UrlService _sut;
/// <summary>
/// Initializes a new instance of the <see cref="UrlServiceTests"/> class.
/// </summary>
public UrlServiceTests()
{
_mockHttpContextAccessor = Substitute.For<IHttpContextAccessor>();
_sut = new UrlService(_mockHttpContextAccessor);
}
[Fact]
public void GetAbsoluteUrl_WhenRouteTemplateIsNotDefined_ShouldThrowArgumentException()
{
// Act
ArgumentException exception = Assert.Throws<ArgumentException>(() => _sut.GetAbsoluteUrl("/not-a-real-route"));
// Assert
Assert.Equal("routeTemplate", exception.ParamName);
Assert.Contains("The route template '/not-a-real-route' is not defined in the WebRoutes constants.", exception.Message);
}
[Fact]
public void GetAbsoluteUrl_WhenHttpContextIsNull_ShouldReturnNull()
{
// Arrange
_mockHttpContextAccessor.HttpContext.Returns((HttpContext?)null);
// Act
string? url = _sut.GetAbsoluteUrl(WebRoutes.Authentication.LOGIN);
// Assert
Assert.Null(url);
}
[Fact]
public void GetAbsoluteUrl_WhenCalled_ShouldReplaceCulturePlaceholderAndBuildAbsoluteUrl()
{
// Arrange
DefaultHttpContext httpContext = TestHttpContextFactory.Create(culture: "en-us");
httpContext.Request.Host = new HostString("localhost:5012");
httpContext.Request.Scheme = "http";
_mockHttpContextAccessor.HttpContext.Returns(httpContext);
// Act
string? url = _sut.GetAbsoluteUrl(WebRoutes.Authentication.LOGIN);
// Assert
Assert.Equal("http://localhost:5012/en-us/auth/api-login", url);
}
[Fact]
public void GetAbsoluteUrl_WhenCalledWithAdditionalRouteValues_ShouldReplacePlaceholders()
{
// Arrange
DefaultHttpContext httpContext = TestHttpContextFactory.Create(culture: "en-us");
httpContext.Request.Host = new HostString("localhost:5012");
httpContext.Request.Scheme = "http";
_mockHttpContextAccessor.HttpContext.Returns(httpContext);
Guid id = Guid.NewGuid();
// Act
string? url = _sut.GetAbsoluteUrl(WebRoutes.LibraryManagement.DELETE_LIBRARY, new { id });
// Assert
Assert.Equal($"http://localhost:5012/en-us/libraries/manage/api-item/{id}", url);
}
[Fact]
public void GetAbsoluteUrl_WhenPathBaseIsPresent_ShouldIncludePathBase()
{
// Arrange
DefaultHttpContext httpContext = TestHttpContextFactory.Create(culture: "de-de");
httpContext.Request.PathBase = "/lumina";
httpContext.Request.Host = new HostString("localhost:5012");
httpContext.Request.Scheme = "https";
_mockHttpContextAccessor.HttpContext.Returns(httpContext);
// Act
string? url = _sut.GetAbsoluteUrl(WebRoutes.Authentication.REGISTER_VIEW);
// Assert
Assert.Equal("https://localhost:5012/lumina/de-de/auth/register", url);
}
[Fact]
public void GetAbsoluteUrl_WhenRouteTemplateDoesNotStartWithSlash_ShouldPrependSlash()
{
// Arrange
DefaultHttpContext httpContext = TestHttpContextFactory.Create(culture: "en-us");
httpContext.Request.Host = new HostString("localhost:5012");
httpContext.Request.Scheme = "http";
_mockHttpContextAccessor.HttpContext.Returns(httpContext);
// Act
string? url = _sut.GetAbsoluteUrl(WebRoutes.FileSystem.GET_TYPE);
// Assert
Assert.Equal("http://localhost:5012/file-system/api-get-type", url);
}
[Fact]
public void GetRelativeUrl_WhenRouteTemplateIsNotDefined_ShouldThrowArgumentException()
{
// Act
ArgumentException exception = Assert.Throws<ArgumentException>(() => _sut.GetRelativeUrl("/not-a-real-route"));
// Assert
Assert.Equal("routeTemplate", exception.ParamName);
Assert.Contains("The route template '/not-a-real-route' is not defined in the WebRoutes constants.", exception.Message);
}
[Fact]
public void GetRelativeUrl_WhenHttpContextIsNull_ShouldReturnNull()
{
// Arrange
_mockHttpContextAccessor.HttpContext.Returns((HttpContext?)null);
// Act
string? url = _sut.GetRelativeUrl(WebRoutes.Authentication.LOGIN);
// Assert
Assert.Null(url);
}
[Fact]
public void GetRelativeUrl_WhenCalled_ShouldReturnCultureLocalizedPathWithoutSchemeOrHost()
{
// Arrange
DefaultHttpContext httpContext = TestHttpContextFactory.Create(culture: "en-us");
httpContext.Request.Host = new HostString("localhost:5012");
_mockHttpContextAccessor.HttpContext.Returns(httpContext);
// Act
string? url = _sut.GetRelativeUrl(WebRoutes.Authentication.LOGIN);
// Assert
Assert.Equal("/en-us/auth/api-login", url);
}
[Fact]
public void GetRelativeUrl_WhenCultureRouteValueIsAbsent_ShouldFallBackToDefaultCulture()
{
// Arrange
_mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(culture: null));
// Act
string? url = _sut.GetRelativeUrl(WebRoutes.Authentication.LOGIN);
// Assert
Assert.Equal("/en-US/auth/api-login", url);
}
[Fact]
public void GetRelativeUrl_WhenCalledWithAdditionalRouteValues_ShouldReplacePlaceholders()
{
// Arrange
_mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(culture: "en-us"));
Guid id = Guid.NewGuid();
// Act
string? url = _sut.GetRelativeUrl(WebRoutes.LibraryManagement.DELETE_LIBRARY, new { id });
// Assert
Assert.Equal($"/en-us/libraries/manage/api-item/{id}", url);
}
[Fact]
public void GetRelativeUrl_WhenRouteTemplateDoesNotStartWithSlash_ShouldPrependSlash()
{
// Arrange
_mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(culture: "en-us"));
// Act
string? url = _sut.GetRelativeUrl(WebRoutes.FileSystem.GET_TYPE);
// Assert
Assert.Equal("/file-system/api-get-type", url);
}
[Fact]
public void GetRelativeUrl_WhenPathBaseIsPresent_ShouldIncludePathBaseWithoutSchemeOrHost()
{
// Arrange
DefaultHttpContext httpContext = TestHttpContextFactory.Create(culture: "de-de");
httpContext.Request.PathBase = "/lumina";
httpContext.Request.Host = new HostString("localhost:5012");
httpContext.Request.Scheme = "https";
_mockHttpContextAccessor.HttpContext.Returns(httpContext);
// Act
string? url = _sut.GetRelativeUrl(WebRoutes.Authentication.REGISTER_VIEW);
// Assert
Assert.Equal("/lumina/de-de/auth/register", url);
}
[Fact]
public void GetRelativeUrl_WhenOptionalRouteValueIsNotSupplied_ShouldRemoveOptionalSegment()
{
// Arrange
_mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(culture: "en-us"));
// Act
string? url = _sut.GetRelativeUrl(WebRoutes.Authentication.LOGIN_VIEW);
// Assert
Assert.Equal("/en-us/auth/login", url);
}
[Theory]
[InlineData(null)]
[InlineData("")]
public void GetRelativeUrl_WhenOptionalRouteValueIsEmpty_ShouldRemoveOptionalSegment(string? returnUrl)
{
// Arrange
_mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(culture: "en-us"));
// Act
string? url = _sut.GetRelativeUrl(WebRoutes.Authentication.LOGIN_VIEW, new { returnUrl });
// Assert
Assert.Equal("/en-us/auth/login", url);
}
[Fact]
public void GetRelativeUrl_WhenOptionalRouteValueIsSupplied_ShouldReplaceOptionalPlaceholder()
{
// Arrange
_mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(culture: "en-us"));
// Act
string? url = _sut.GetRelativeUrl(WebRoutes.Authentication.LOGIN_VIEW, new { returnUrl = "libraries" });
// Assert
Assert.Equal("/en-us/auth/login/libraries", url);
}
[Fact]
public void GetAbsoluteUrl_WhenOptionalRouteValueIsNotSupplied_ShouldBuildWellFormedUrl()
{
// Arrange
DefaultHttpContext httpContext = TestHttpContextFactory.Create(culture: "en-us");
httpContext.Request.Host = new HostString("localhost:5012");
httpContext.Request.Scheme = "http";
_mockHttpContextAccessor.HttpContext.Returns(httpContext);
// Act
string? url = _sut.GetAbsoluteUrl(WebRoutes.Authentication.LOGIN_VIEW);
// Assert
Assert.Equal("http://localhost:5012/en-us/auth/login", url);
}
[Fact]
public void GetAbsoluteUrl_WhenCalled_ShouldComposeSchemeAndHostWithRelativeUrl()
{
// Arrange
DefaultHttpContext httpContext = TestHttpContextFactory.Create(culture: "de-de");
httpContext.Request.PathBase = "/lumina";
httpContext.Request.Host = new HostString("localhost:5012");
httpContext.Request.Scheme = "https";
_mockHttpContextAccessor.HttpContext.Returns(httpContext);
Guid id = Guid.NewGuid();
// Act
string? relativeUrl = _sut.GetRelativeUrl(WebRoutes.LibraryManagement.DELETE_LIBRARY, new { id });
string? absoluteUrl = _sut.GetAbsoluteUrl(WebRoutes.LibraryManagement.DELETE_LIBRARY, new { id });
// Assert
Assert.NotNull(relativeUrl);
Assert.Equal($"https://localhost:5012{relativeUrl}", absoluteUrl);
}
}
@@ -0,0 +1,56 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Primitives;
using Lumina.Presentation.Web.Common.Validation;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Common.Setup;
/// <summary>
/// Validator extension methods for <see cref="IValidator{TRequest}"/> for unit tests.
/// </summary>
[ExcludeFromCodeCoverage]
public static class ValidatorTestExtensions
{
/// <summary>
/// Executes the validator against the specified request instance and returns the resulting errors.
/// </summary>
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
/// <param name="validator">The validator instance to execute.</param>
/// <param name="request">The request instance to validate.</param>
/// <returns>A list of <see cref="Error"/> produced by the validator. If the request is valid, the list will be empty.</returns>
public static List<Error> TestValidate<TRequest>(this IValidator<TRequest> validator, TRequest request)
{
return validator.Validate(request);
}
/// <summary>
/// Asserts that the validation results do not contain the specified error.
/// </summary>
/// <param name="errors">The list of errors returned by the validator.</param>
/// <param name="expectedError">The error that should not be present in the validation results.</param>
public static void ShouldNotHaveValidationError(this List<Error> errors, Error expectedError)
{
Assert.DoesNotContain(errors, error => error.Description == expectedError.Description);
}
/// <summary>
/// Asserts that the validation results contain the specified error.
/// </summary>
/// <param name="errors">The list of errors returned by the validator.</param>
/// <param name="expectedError">The error that should be present in the validation results.</param>
public static void ShouldHaveValidationError(this List<Error> errors, Error expectedError)
{
Assert.Contains(errors, error => error.Description == expectedError.Description);
}
/// <summary>
/// Asserts that the validation results are completely empty, indicating the request is valid.
/// </summary>
/// <param name="errors">The list of errors returned by the validator.</param>
public static void ShouldNotHaveAnyValidationErrors(this List<Error> errors)
{
Assert.Empty(errors);
}
}
@@ -0,0 +1,143 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Primitives;
using Lumina.Presentation.Web.Common.Validation;
using Lumina.Presentation.Web.Fixtures.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
{
private readonly ValidationOptionsFixture _validationOptionsFixture = new();
[Fact]
public void Validate_WhenMatchingName_ShouldValidateOptions()
{
// Arrange
string optionsName = "OptionsName";
ValidationOptionsFixture options = _validationOptionsFixture.Create();
IValidator<ValidationOptionsFixture> validator = Substitute.For<IValidator<ValidationOptionsFixture>>();
validator.Validate(options).Returns([]);
ValidationOptions<ValidationOptionsFixture> 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";
ValidationOptionsFixture options = _validationOptionsFixture.Create();
IValidator<ValidationOptionsFixture> validator = Substitute.For<IValidator<ValidationOptionsFixture>>();
ValidationOptions<ValidationOptionsFixture> 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
ValidationOptionsFixture options = _validationOptionsFixture.Create();
IValidator<ValidationOptionsFixture> validator = Substitute.For<IValidator<ValidationOptionsFixture>>();
validator.Validate(options).Returns([]);
ValidationOptions<ValidationOptionsFixture> 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<ValidationOptionsFixture> validator = Substitute.For<IValidator<ValidationOptionsFixture>>();
ValidationOptions<ValidationOptionsFixture> sut = new(optionsName, validator);
// Act
Action act = () => sut.Validate(optionsName, null!);
// Assert
Assert.Throws<ArgumentNullException>(act);
validator.DidNotReceive().Validate(Arg.Any<ValidationOptionsFixture>());
}
[Fact]
public void Validate_WhenInvalidOptions_ShouldReturnFailureResult()
{
// Arrange
string optionsName = "OptionsName";
ValidationOptionsFixture options = _validationOptionsFixture.Create();
IValidator<ValidationOptionsFixture> validator = Substitute.For<IValidator<ValidationOptionsFixture>>();
List<Error> validationFailures =
[
Error.Validation("PropertyName", "Error Message")
];
validator.Validate(options).Returns(validationFailures);
ValidationOptions<ValidationOptionsFixture> 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";
ValidationOptionsFixture options = _validationOptionsFixture.Create();
IValidator<ValidationOptionsFixture> validator = Substitute.For<IValidator<ValidationOptionsFixture>>();
List<Error> validationFailures =
[
Error.Validation("PropertyOne", "First Error Message"),
Error.Validation("PropertyTwo", "Second Error Message")
];
validator.Validate(options).Returns(validationFailures);
ValidationOptions<ValidationOptionsFixture> 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);
}
}
@@ -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";
}
}
@@ -0,0 +1,61 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.DTO.Configuration;
using Lumina.Presentation.Web.Common.Primitives;
using Lumina.Presentation.Web.Common.Validators;
using Lumina.Presentation.Web.Fixtures.Common.DTO.Configuration;
using Lumina.Presentation.Web.UnitTests.Common.Setup;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Common.Validators;
/// <summary>
/// Contains unit tests for the <see cref="EncryptionSettingsDtoValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class EncryptionSettingsModelValidatorTests
{
private const string VALID_BASE64_KEY = "FLYO0QRo6u2VzoFOgNkkEwYNGtqhJ3QGZd7iAHNEJeM=";
private readonly EncryptionSettingsDtoFixture _encryptionSettingsDtoFixture = new();
private readonly EncryptionSettingsDtoValidator _validator = new();
[Fact]
public void Validate_WhenSecretKeyIsEmpty_ShouldHaveValidationError()
{
// Arrange
EncryptionSettingsDto settings = _encryptionSettingsDtoFixture.Create(secretKey: string.Empty);
// Act
List<Error> result = _validator.TestValidate(settings);
// Assert
result.ShouldHaveValidationError(Error.Validation(description: "Encryption secret key cannot be empty!"));
}
[Fact]
public void Validate_WhenSecretKeyIsNotBase64_ShouldHaveValidationError()
{
// Arrange
EncryptionSettingsDto settings = _encryptionSettingsDtoFixture.Create(secretKey: "not-base64-key!");
// Act
List<Error> result = _validator.TestValidate(settings);
// Assert
result.ShouldHaveValidationError(Error.Validation(description: "Encryption secret key must be a base64 string!"));
}
[Fact]
public void Validate_WhenSecretKeyIsValidBase64_ShouldNotHaveValidationError()
{
// Arrange
EncryptionSettingsDto settings = _encryptionSettingsDtoFixture.Create(secretKey: VALID_BASE64_KEY);
// Act
List<Error> result = _validator.TestValidate(settings);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
}
@@ -0,0 +1,77 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.DTO.Configuration;
using Lumina.Presentation.Web.Common.Primitives;
using Lumina.Presentation.Web.Common.Validators;
using Lumina.Presentation.Web.Fixtures.Common.DTO.Configuration;
using Lumina.Presentation.Web.UnitTests.Common.Setup;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Common.Validators;
/// <summary>
/// Contains unit tests for the <see cref="ServerConfigurationDtoValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ServerConfigurationModelValidatorTests
{
private readonly ServerConfigurationDtoFixture _serverConfigurationDtoFixture = new();
private readonly ServerConfigurationDtoValidator _validator = new();
[Fact]
public void Validate_WhenBaseAddressIsEmpty_ShouldHaveValidationError()
{
// Arrange
ServerConfigurationDto configuration = _serverConfigurationDtoFixture.Create(apiVersion: '1', baseAddress: string.Empty, port: 5214);
// Act
List<Error> result = _validator.TestValidate(configuration);
// Assert
result.ShouldHaveValidationError(Error.Validation(description: "Base address cannot be empty!"));
}
[Theory]
[InlineData((ushort)0)] // Minimum allowed value.
[InlineData((ushort)65535)] // Maximum allowed value.
public void Validate_WhenPortIsAtBoundary_ShouldNotHaveValidationError(ushort port)
{
// Arrange
ServerConfigurationDto configuration = _serverConfigurationDtoFixture.Create(apiVersion: '1', baseAddress: "http://localhost", port: port);
// Act
List<Error> result = _validator.TestValidate(configuration);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
[Theory]
[InlineData((char)0)] // Minimum allowed API version.
[InlineData((char)255)] // Maximum allowed API version.
public void Validate_WhenApiVersionIsAtBoundary_ShouldNotHaveValidationError(char apiVersion)
{
// Arrange
ServerConfigurationDto configuration = _serverConfigurationDtoFixture.Create(apiVersion: apiVersion, baseAddress: "http://localhost", port: 5214);
// Act
List<Error> result = _validator.TestValidate(configuration);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
[Fact]
public void Validate_WhenConfigurationIsValid_ShouldNotHaveValidationError()
{
// Arrange
ServerConfigurationDto configuration = _serverConfigurationDtoFixture.Create(apiVersion: '1', baseAddress: "http://localhost", port: 5214);
// Act
List<Error> result = _validator.TestValidate(configuration);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
}