mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 10:11:10 +00:00
Renames project paths from Lumina to Nemera
This commit is contained in:
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))];
|
||||
}
|
||||
}
|
||||
+374
@@ -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")
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user