mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 04:11:10 +00:00
Implements tests for commit 45f9aa3bd5
This commit is contained in:
1 parent
d61a114d80
commit
aeefa9487e
44 files changed
+6929
-18
No files matched your search
@@ -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,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))];
|
||||
}
|
||||
}
|
||||
+57
@@ -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);
|
||||
}
|
||||
}
|
||||
+261
@@ -0,0 +1,261 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetPlaybackManifest;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetPlaybackManifest;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetPlaybackManifestEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetPlaybackManifestEndpointTests
|
||||
{
|
||||
private const string VALID_DELIVERY_ID = "0123456789abcdef0123456789abcdef";
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly GetPlaybackManifestEndpoint _sut;
|
||||
private readonly GetPlaybackManifestRequestFixture _getPlaybackManifestRequestFixture = new();
|
||||
private readonly PlaybackManifestDtoFixture _playbackManifestDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPlaybackManifestEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetPlaybackManifestEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<GetPlaybackManifestEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenManifestIsNotADirectPlay_ShouldRewriteTheStreamPathsToTheWebProxyRoutes()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
string artistId = Guid.NewGuid().ToString();
|
||||
string albumId = Guid.NewGuid().ToString();
|
||||
string trackId = Guid.NewGuid().ToString();
|
||||
GetPlaybackManifestRequest request = _getPlaybackManifestRequestFixture.Create(
|
||||
artistId: artistId,
|
||||
albumId: albumId,
|
||||
trackId: trackId,
|
||||
libraryId: libraryId,
|
||||
includeCapabilities: false);
|
||||
PlaybackManifestDto manifest = _playbackManifestDtoFixture.Create(
|
||||
isDirectPlay: false,
|
||||
deliveryId: VALID_DELIVERY_ID,
|
||||
streamPath: "/api/v1/libraries/ancient/stream",
|
||||
segmentStreamPathTemplate: "/api/v1/libraries/ancient/stream/deliveries/{deliveryId}/segments/{segmentIndex}");
|
||||
_mockApiHttpClient.GetAsync<PlaybackManifestDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(manifest);
|
||||
string expectedStreamPath = $"/en-US/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-stream-track?libraryId={libraryId}";
|
||||
string expectedSegmentStreamPathTemplate = $"/en-US/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-stream-track-segment/{{deliveryId}}/{{segmentIndex}}?libraryId={libraryId}";
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
using JsonDocument json = JsonDocument.Parse(await JsonResultTestHelper.GetResponseBodyAsync(result));
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
JsonElement data = json.RootElement.GetProperty("data");
|
||||
Assert.Equal(expectedStreamPath, data.GetProperty("streamPath").GetString());
|
||||
Assert.Equal(expectedSegmentStreamPathTemplate, data.GetProperty("segmentStreamPathTemplate").GetString());
|
||||
Assert.Equal(VALID_DELIVERY_ID, data.GetProperty("deliveryId").GetString());
|
||||
Assert.DoesNotContain("http", data.GetProperty("streamPath").GetString(), StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("http", data.GetProperty("segmentStreamPathTemplate").GetString(), StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString());
|
||||
Assert.Equal("Cookie", _sut.HttpContext.Response.Headers["Vary"].ToString());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(true)] // a null template means the delivery has no segment route
|
||||
[InlineData(false)] // an empty template means the delivery has no segment route
|
||||
public async Task ExecuteAsync_WhenSegmentPathTemplateIsEmpty_ShouldClearTheDeliveryIdAndTheTemplate(bool useNullTemplate)
|
||||
{
|
||||
// Arrange
|
||||
GetPlaybackManifestRequest request = _getPlaybackManifestRequestFixture.Create(includeCapabilities: false);
|
||||
PlaybackManifestDto manifest = _playbackManifestDtoFixture.Create(
|
||||
isDirectPlay: false,
|
||||
deliveryId: VALID_DELIVERY_ID,
|
||||
segmentStreamPathTemplate: useNullTemplate ? null : string.Empty,
|
||||
includeSegmentStreamPathTemplate: !useNullTemplate);
|
||||
_mockApiHttpClient.GetAsync<PlaybackManifestDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(manifest);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
using JsonDocument json = JsonDocument.Parse(await JsonResultTestHelper.GetResponseBodyAsync(result));
|
||||
JsonElement data = json.RootElement.GetProperty("data");
|
||||
Assert.Equal(JsonValueKind.Null, data.GetProperty("deliveryId").ValueKind);
|
||||
Assert.Equal(JsonValueKind.Null, data.GetProperty("segmentStreamPathTemplate").ValueKind);
|
||||
Assert.NotEqual(JsonValueKind.Null, data.GetProperty("streamPath").ValueKind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSegmentPathTemplateIsPresentButDeliveryIdIsInvalid_ShouldThrowBadGatewayApiException()
|
||||
{
|
||||
// Arrange
|
||||
GetPlaybackManifestRequest request = _getPlaybackManifestRequestFixture.Create(includeCapabilities: false);
|
||||
PlaybackManifestDto manifest = _playbackManifestDtoFixture.Create(
|
||||
isDirectPlay: false,
|
||||
deliveryId: "not-a-valid-handle",
|
||||
segmentStreamPathTemplate: "/api/v1/libraries/ancient/stream/deliveries/{deliveryId}/segments/{segmentIndex}");
|
||||
_mockApiHttpClient.GetAsync<PlaybackManifestDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(manifest);
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
ApiException apiException = await Assert.ThrowsAsync<ApiException>(() => operationTask);
|
||||
Assert.Equal(HttpStatusCode.BadGateway, apiException.HttpStatusCode);
|
||||
Assert.NotNull(apiException.ProblemDetails);
|
||||
Assert.Equal("General.Failure", apiException.ProblemDetails!.Title);
|
||||
Assert.Equal("InternalServerError", apiException.ProblemDetails.Detail);
|
||||
Assert.Equal(StatusCodes.Status502BadGateway, apiException.ProblemDetails.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsNoManifest_ShouldThrowBadGatewayApiException()
|
||||
{
|
||||
// Arrange
|
||||
GetPlaybackManifestRequest request = _getPlaybackManifestRequestFixture.Create(includeCapabilities: false);
|
||||
_mockApiHttpClient.GetAsync<PlaybackManifestDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromResult<PlaybackManifestDto>(null!));
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
ApiException apiException = await Assert.ThrowsAsync<ApiException>(() => operationTask);
|
||||
Assert.Equal(HttpStatusCode.BadGateway, apiException.HttpStatusCode);
|
||||
Assert.NotNull(apiException.ProblemDetails);
|
||||
Assert.Equal("General.Failure", apiException.ProblemDetails!.Title);
|
||||
Assert.Equal("InternalServerError", apiException.ProblemDetails.Detail);
|
||||
Assert.Equal(StatusCodes.Status502BadGateway, apiException.ProblemDetails.Status);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("mp3/mp3", "?capabilities=mp3%2Fmp3")] // the capabilities are forwarded and URL-escaped
|
||||
[InlineData("flac/flac,mp3/mp3", "?capabilities=flac%2Fflac%2Cmp3%2Fmp3")] // a capability list is forwarded as one escaped value
|
||||
[InlineData(" ", "")] // whitespace only capabilities are not forwarded
|
||||
[InlineData(null, "")] // absent capabilities are not forwarded
|
||||
public async Task ExecuteAsync_WhenCapabilitiesAreProvided_ShouldForwardThemOnlyWhenTheyAreNotEmpty(string? capabilities, string expectedSuffix)
|
||||
{
|
||||
// Arrange
|
||||
string artistId = Guid.NewGuid().ToString();
|
||||
string albumId = Guid.NewGuid().ToString();
|
||||
string trackId = Guid.NewGuid().ToString();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
GetPlaybackManifestRequest request = _getPlaybackManifestRequestFixture.Create(
|
||||
artistId: artistId,
|
||||
albumId: albumId,
|
||||
trackId: trackId,
|
||||
libraryId: libraryId,
|
||||
capabilities: capabilities,
|
||||
includeCapabilities: capabilities is not null);
|
||||
string expectedEndpoint = ApiRoutes.Music.GET_PLAYBACK_MANIFEST
|
||||
.Replace("{libraryId}", libraryId.ToString())
|
||||
.Replace("{artistId}", artistId)
|
||||
.Replace("{albumId}", albumId)
|
||||
.Replace("{trackId}", trackId) + expectedSuffix;
|
||||
_mockApiHttpClient.GetAsync<PlaybackManifestDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_playbackManifestDtoFixture.Create(deliveryId: VALID_DELIVERY_ID));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PlaybackManifestDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == expectedEndpoint),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteIdsAreNotParseable_ShouldForwardEmptyGuidsToTheApi()
|
||||
{
|
||||
// Arrange
|
||||
GetPlaybackManifestRequest request = _getPlaybackManifestRequestFixture.Create(artistId: "not-a-guid", albumId: "' OR '1'='1", trackId: "'; DROP TABLE Tracks; --", includeCapabilities: false);
|
||||
string expectedEndpoint = ApiRoutes.Music.GET_PLAYBACK_MANIFEST
|
||||
.Replace("{libraryId}", request.LibraryId.ToString())
|
||||
.Replace("{artistId}", Guid.Empty.ToString())
|
||||
.Replace("{albumId}", Guid.Empty.ToString())
|
||||
.Replace("{trackId}", Guid.Empty.ToString());
|
||||
_mockApiHttpClient.GetAsync<PlaybackManifestDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_playbackManifestDtoFixture.Create(deliveryId: VALID_DELIVERY_ID));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PlaybackManifestDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == expectedEndpoint),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("/lumina", "/lumina")] // a plain absolute path base is prefixed
|
||||
[InlineData("//evil", "")] // a protocol relative path base would point the stream at another origin
|
||||
[InlineData("/a?b", "")] // a path base with a query would truncate the built path
|
||||
public async Task ExecuteAsync_WhenPathBaseIsPresent_ShouldUseItOnlyWhenItIsSafe(string pathBase, string expectedPrefix)
|
||||
{
|
||||
// Arrange
|
||||
GetPlaybackManifestRequest request = _getPlaybackManifestRequestFixture.Create(includeCapabilities: false);
|
||||
_sut.HttpContext.Request.PathBase = pathBase;
|
||||
_mockApiHttpClient.GetAsync<PlaybackManifestDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_playbackManifestDtoFixture.Create(deliveryId: VALID_DELIVERY_ID));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
using JsonDocument json = JsonDocument.Parse(await JsonResultTestHelper.GetResponseBodyAsync(result));
|
||||
string? streamPath = json.RootElement.GetProperty("data").GetProperty("streamPath").GetString();
|
||||
Assert.NotNull(streamPath);
|
||||
Assert.StartsWith($"{expectedPrefix}/en-US/library/audio-library/music-library/artists/", streamPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
GetPlaybackManifestRequest request = _getPlaybackManifestRequestFixture.Create(includeCapabilities: false);
|
||||
CancellationTokenSource cancellationTokenSource = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
_mockApiHttpClient.GetAsync<PlaybackManifestDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return _playbackManifestDtoFixture.Create(deliveryId: VALID_DELIVERY_ID);
|
||||
}, callInfo.Arg<CancellationToken>()));
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(request, cancellationTokenSource.Token);
|
||||
await operationStarted.Task;
|
||||
cancellationTokenSource.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
}
|
||||
+223
@@ -0,0 +1,223 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.StreamMusicTrack;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
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.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.StreamMusicTrack;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="StreamMusicTrackEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class StreamMusicTrackEndpointTests
|
||||
{
|
||||
private readonly IStreamingApiHttpClient _mockStreamingApiHttpClient;
|
||||
private readonly StreamMusicTrackEndpoint _sut;
|
||||
private readonly StreamMusicTrackRequestFixture _streamMusicTrackRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="StreamMusicTrackEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public StreamMusicTrackEndpointTests()
|
||||
{
|
||||
_mockStreamingApiHttpClient = Substitute.For<IStreamingApiHttpClient>();
|
||||
_sut = Factory.Create<StreamMusicTrackEndpoint>(_mockStreamingApiHttpClient);
|
||||
_sut.HttpContext.Response.Body = new MemoryStream();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldStreamTheTrackAndReturnEmptyResult()
|
||||
{
|
||||
// Arrange
|
||||
StreamMusicTrackRequest request = _streamMusicTrackRequestFixture.Create();
|
||||
string expectedEndpoint = BuildExpectedEndpoint(request);
|
||||
byte[] contentBytes = CreateBytes(1024);
|
||||
ApiStreamResult streamResult = await CreateStreamResultAsync(HttpStatusCode.OK, contentBytes, "audio/flac");
|
||||
_mockStreamingApiHttpClient.GetStreamAsync(Arg.Any<string>(), Arg.Any<IReadOnlyDictionary<string, string>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(streamResult);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.IsType<EmptyHttpResult>(result);
|
||||
await _mockStreamingApiHttpClient.Received(1).GetStreamAsync(
|
||||
Arg.Is<string>(endpoint => endpoint == expectedEndpoint),
|
||||
Arg.Any<IReadOnlyDictionary<string, string>>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
Assert.Equal(StatusCodes.Status200OK, _sut.HttpContext.Response.StatusCode);
|
||||
Assert.Equal("audio/flac", _sut.HttpContext.Response.ContentType);
|
||||
Assert.Equal(contentBytes.Length, _sut.HttpContext.Response.ContentLength);
|
||||
Assert.Equal(contentBytes, ReadResponseBody(_sut.HttpContext));
|
||||
Assert.Equal("Cookie", _sut.HttpContext.Response.Headers["Vary"].ToString());
|
||||
Assert.Contains("private", _sut.HttpContext.Response.Headers["Cache-Control"].ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenConditionalHeadersArePresent_ShouldForwardThemExactly()
|
||||
{
|
||||
// Arrange
|
||||
StreamMusicTrackRequest request = _streamMusicTrackRequestFixture.Create();
|
||||
_sut.HttpContext.Request.Headers["Range"] = "bytes=100-199";
|
||||
_sut.HttpContext.Request.Headers["If-Range"] = "\"etag-value\"";
|
||||
_sut.HttpContext.Request.Headers["If-None-Match"] = "\"etag-value\"";
|
||||
_sut.HttpContext.Request.Headers["If-Modified-Since"] = "Wed, 21 Oct 2015 07:28:00 GMT";
|
||||
_mockStreamingApiHttpClient.GetStreamAsync(Arg.Any<string>(), Arg.Any<IReadOnlyDictionary<string, string>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(await CreateStreamResultAsync(HttpStatusCode.OK, CreateBytes(16)));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockStreamingApiHttpClient.Received(1).GetStreamAsync(
|
||||
Arg.Any<string>(),
|
||||
Arg.Is<IReadOnlyDictionary<string, string>>(headers =>
|
||||
headers.Count == 4 &&
|
||||
headers["Range"] == "bytes=100-199" &&
|
||||
headers["If-Range"] == "\"etag-value\"" &&
|
||||
headers["If-None-Match"] == "\"etag-value\"" &&
|
||||
headers["If-Modified-Since"] == "Wed, 21 Oct 2015 07:28:00 GMT"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenConditionalHeadersAreAbsentOrWhitespace_ShouldNotForwardThem()
|
||||
{
|
||||
// Arrange
|
||||
StreamMusicTrackRequest request = _streamMusicTrackRequestFixture.Create();
|
||||
_sut.HttpContext.Request.Headers["Range"] = " ";
|
||||
_mockStreamingApiHttpClient.GetStreamAsync(Arg.Any<string>(), Arg.Any<IReadOnlyDictionary<string, string>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(await CreateStreamResultAsync(HttpStatusCode.OK, CreateBytes(16)));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockStreamingApiHttpClient.Received(1).GetStreamAsync(
|
||||
Arg.Any<string>(),
|
||||
Arg.Is<IReadOnlyDictionary<string, string>>(headers => headers.Count == 0),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteIdsAreNotParseable_ShouldForwardEmptyGuidsToTheApi()
|
||||
{
|
||||
// Arrange
|
||||
StreamMusicTrackRequest request = _streamMusicTrackRequestFixture.Create(artistId: "not-a-guid", albumId: "' OR '1'='1", trackId: "'; DROP TABLE Tracks; --");
|
||||
string expectedEndpoint = ApiRoutes.Music.STREAM_TRACK
|
||||
.Replace("{libraryId}", request.LibraryId.ToString())
|
||||
.Replace("{artistId}", Guid.Empty.ToString())
|
||||
.Replace("{albumId}", Guid.Empty.ToString())
|
||||
.Replace("{trackId}", Guid.Empty.ToString());
|
||||
_mockStreamingApiHttpClient.GetStreamAsync(Arg.Any<string>(), Arg.Any<IReadOnlyDictionary<string, string>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(await CreateStreamResultAsync(HttpStatusCode.OK, CreateBytes(8)));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockStreamingApiHttpClient.Received(1).GetStreamAsync(
|
||||
Arg.Is<string>(endpoint => endpoint == expectedEndpoint),
|
||||
Arg.Any<IReadOnlyDictionary<string, string>>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
StreamMusicTrackRequest request = _streamMusicTrackRequestFixture.Create();
|
||||
CancellationTokenSource cancellationTokenSource = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
_mockStreamingApiHttpClient.GetStreamAsync(Arg.Any<string>(), Arg.Any<IReadOnlyDictionary<string, string>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return await CreateStreamResultAsync(HttpStatusCode.OK, CreateBytes(8));
|
||||
}, callInfo.Arg<CancellationToken>()));
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(request, cancellationTokenSource.Token);
|
||||
await operationStarted.Task;
|
||||
cancellationTokenSource.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the upstream endpoint the track stream request is expected to be sent to.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to build the endpoint for.</param>
|
||||
/// <returns>The expected upstream endpoint.</returns>
|
||||
private static string BuildExpectedEndpoint(StreamMusicTrackRequest request)
|
||||
{
|
||||
return ApiRoutes.Music.STREAM_TRACK
|
||||
.Replace("{libraryId}", request.LibraryId.ToString())
|
||||
.Replace("{artistId}", request.ArtistId)
|
||||
.Replace("{albumId}", request.AlbumId)
|
||||
.Replace("{trackId}", request.TrackId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a streamed API response with a status code, a body and an optional media type.
|
||||
/// </summary>
|
||||
/// <param name="statusCode">The status code of the response.</param>
|
||||
/// <param name="contentBytes">The bytes of the content of the response.</param>
|
||||
/// <param name="contentType">The optional media type of the content.</param>
|
||||
/// <returns>The created streamed response.</returns>
|
||||
private static async Task<ApiStreamResult> CreateStreamResultAsync(HttpStatusCode statusCode, byte[] contentBytes, string? contentType = null)
|
||||
{
|
||||
HttpResponseMessage response = new(statusCode)
|
||||
{
|
||||
Content = new ByteArrayContent(contentBytes)
|
||||
};
|
||||
if (contentType is not null)
|
||||
response.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
|
||||
return await ApiStreamResult.CreateAsync(response, CancellationToken.None);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the bytes written to the response body of the provided HTTP context.
|
||||
/// </summary>
|
||||
/// <param name="httpContext">The HTTP context whose response body is read.</param>
|
||||
/// <returns>The bytes written to the response body.</returns>
|
||||
private static byte[] ReadResponseBody(HttpContext httpContext)
|
||||
{
|
||||
httpContext.Response.Body.Position = 0;
|
||||
using MemoryStream writtenBody = new();
|
||||
httpContext.Response.Body.CopyTo(writtenBody);
|
||||
return writtenBody.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a deterministic byte array that stands in for the content of a track.
|
||||
/// </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))];
|
||||
}
|
||||
}
|
||||
+265
@@ -0,0 +1,265 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.StreamMusicTrackSegment;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Globalization;
|
||||
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.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.StreamMusicTrackSegment;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="StreamMusicTrackSegmentEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class StreamMusicTrackSegmentEndpointTests
|
||||
{
|
||||
private readonly IStreamingApiHttpClient _mockStreamingApiHttpClient;
|
||||
private readonly StreamMusicTrackSegmentEndpoint _sut;
|
||||
private readonly StreamMusicTrackSegmentRequestFixture _streamMusicTrackSegmentRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="StreamMusicTrackSegmentEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public StreamMusicTrackSegmentEndpointTests()
|
||||
{
|
||||
_mockStreamingApiHttpClient = Substitute.For<IStreamingApiHttpClient>();
|
||||
_sut = Factory.Create<StreamMusicTrackSegmentEndpoint>(_mockStreamingApiHttpClient);
|
||||
_sut.HttpContext.Response.Body = new MemoryStream();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("uppercase")] // the handle format only accepts lowercase hexadecimal characters
|
||||
[InlineData("dashed")] // the handle format is the N format of a GUID, without dashes
|
||||
[InlineData("short")] // a handle that is shorter than the format allows
|
||||
public async Task ExecuteAsync_WhenDeliveryIdIsInvalid_ShouldReturnNotFoundWithoutCallingTheApi(string malformedHandleKind)
|
||||
{
|
||||
// Arrange
|
||||
string validDeliveryId = Guid.NewGuid().ToString("N");
|
||||
string malformedDeliveryId = malformedHandleKind switch
|
||||
{
|
||||
"uppercase" => validDeliveryId.ToUpperInvariant(),
|
||||
"dashed" => Guid.Parse(validDeliveryId).ToString("D"),
|
||||
_ => validDeliveryId[..31],
|
||||
};
|
||||
StreamMusicTrackSegmentRequest request = _streamMusicTrackSegmentRequestFixture.Create(deliveryId: malformedDeliveryId);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.IsType<EmptyHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, _sut.HttpContext.Response.StatusCode);
|
||||
Assert.Equal(0, _sut.HttpContext.Response.ContentLength);
|
||||
Assert.Equal(0, _sut.HttpContext.Response.Body.Length);
|
||||
await _mockStreamingApiHttpClient.DidNotReceive().GetStreamAsync(
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<IReadOnlyDictionary<string, string>>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRequestIsValid_ShouldStreamTheSegmentFromTheApi()
|
||||
{
|
||||
// Arrange
|
||||
StreamMusicTrackSegmentRequest request = _streamMusicTrackSegmentRequestFixture.Create();
|
||||
string expectedEndpoint = BuildExpectedEndpoint(request);
|
||||
byte[] contentBytes = CreateBytes(512);
|
||||
ApiStreamResult streamResult = await CreateStreamResultAsync(HttpStatusCode.PartialContent, contentBytes, "audio/mp4");
|
||||
_mockStreamingApiHttpClient.GetStreamAsync(Arg.Any<string>(), Arg.Any<IReadOnlyDictionary<string, string>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(streamResult);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.IsType<EmptyHttpResult>(result);
|
||||
await _mockStreamingApiHttpClient.Received(1).GetStreamAsync(
|
||||
Arg.Is<string>(endpoint => endpoint == expectedEndpoint),
|
||||
Arg.Is<IReadOnlyDictionary<string, string>>(headers => headers.Count == 0),
|
||||
Arg.Any<CancellationToken>());
|
||||
Assert.Equal(StatusCodes.Status206PartialContent, _sut.HttpContext.Response.StatusCode);
|
||||
Assert.Equal("audio/mp4", _sut.HttpContext.Response.ContentType);
|
||||
Assert.Equal(contentBytes.Length, _sut.HttpContext.Response.ContentLength);
|
||||
Assert.Equal(contentBytes, ReadResponseBody(_sut.HttpContext));
|
||||
Assert.Equal("Cookie", _sut.HttpContext.Response.Headers["Vary"].ToString());
|
||||
Assert.Contains("private", _sut.HttpContext.Response.Headers["Cache-Control"].ToString());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("artistId", "' OR '1'='1")] // an unparseable artist Id is normalized to an empty GUID
|
||||
[InlineData("albumId", "'; DROP TABLE Tracks; --")] // an unparseable album Id is normalized to an empty GUID
|
||||
[InlineData("trackId", "not-a-guid")] // an unparseable track Id is normalized to an empty GUID
|
||||
public async Task ExecuteAsync_WhenRouteIdsAreNotParseable_ShouldForwardEmptyGuidsToTheApi(string routeValue, string invalidValue)
|
||||
{
|
||||
// Arrange
|
||||
StreamMusicTrackSegmentRequest request = routeValue switch
|
||||
{
|
||||
"artistId" => _streamMusicTrackSegmentRequestFixture.Create(artistId: invalidValue),
|
||||
"albumId" => _streamMusicTrackSegmentRequestFixture.Create(albumId: invalidValue),
|
||||
_ => _streamMusicTrackSegmentRequestFixture.Create(trackId: invalidValue),
|
||||
};
|
||||
string expectedEndpoint = ApiRoutes.Music.STREAM_TRACK_SEGMENT
|
||||
.Replace("{libraryId}", request.LibraryId.ToString())
|
||||
.Replace("{artistId}", routeValue == "artistId" ? Guid.Empty.ToString() : request.ArtistId)
|
||||
.Replace("{albumId}", routeValue == "albumId" ? Guid.Empty.ToString() : request.AlbumId)
|
||||
.Replace("{trackId}", routeValue == "trackId" ? Guid.Empty.ToString() : request.TrackId)
|
||||
.Replace("{deliveryId}", request.DeliveryId)
|
||||
.Replace("{segmentIndex}", request.SegmentIndex.ToString(CultureInfo.InvariantCulture));
|
||||
_mockStreamingApiHttpClient.GetStreamAsync(Arg.Any<string>(), Arg.Any<IReadOnlyDictionary<string, string>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(await CreateStreamResultAsync(HttpStatusCode.OK, CreateBytes(8), "audio/mpeg"));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockStreamingApiHttpClient.Received(1).GetStreamAsync(
|
||||
Arg.Is<string>(endpoint => endpoint == expectedEndpoint),
|
||||
Arg.Any<IReadOnlyDictionary<string, string>>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(HttpStatusCode.ServiceUnavailable)] // a busy normalization pipeline is a transient condition
|
||||
[InlineData(HttpStatusCode.TooManyRequests)] // the stream concurrency limit was reached
|
||||
public async Task ExecuteAsync_WhenApiReportsATransientCondition_ShouldReturnABareStatusWithoutThrowing(HttpStatusCode statusCode)
|
||||
{
|
||||
// Arrange
|
||||
StreamMusicTrackSegmentRequest request = _streamMusicTrackSegmentRequestFixture.Create();
|
||||
ApiException apiException = new(
|
||||
new ProblemDetailsDto { Title = "General.Failure", Detail = "InternalServerError", Status = (int)statusCode },
|
||||
statusCode,
|
||||
BuildExpectedEndpoint(request));
|
||||
_mockStreamingApiHttpClient.GetStreamAsync(Arg.Any<string>(), Arg.Any<IReadOnlyDictionary<string, string>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromException<ApiStreamResult>(apiException));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.IsType<EmptyHttpResult>(result);
|
||||
Assert.Equal((int)statusCode, _sut.HttpContext.Response.StatusCode);
|
||||
Assert.Equal(0, _sut.HttpContext.Response.ContentLength);
|
||||
Assert.Equal(0, _sut.HttpContext.Response.Body.Length);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReportsAnUnexpectedFailure_ShouldPropagateTheApiException()
|
||||
{
|
||||
// Arrange
|
||||
StreamMusicTrackSegmentRequest request = _streamMusicTrackSegmentRequestFixture.Create();
|
||||
ApiException apiException = new(
|
||||
new ProblemDetailsDto { Title = "General.Failure", Detail = "InternalServerError", Status = StatusCodes.Status500InternalServerError },
|
||||
HttpStatusCode.InternalServerError,
|
||||
BuildExpectedEndpoint(request));
|
||||
_mockStreamingApiHttpClient.GetStreamAsync(Arg.Any<string>(), Arg.Any<IReadOnlyDictionary<string, string>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromException<ApiStreamResult>(apiException));
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAsync<ApiException>(() => operationTask);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
StreamMusicTrackSegmentRequest request = _streamMusicTrackSegmentRequestFixture.Create();
|
||||
CancellationTokenSource cancellationTokenSource = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
_mockStreamingApiHttpClient.GetStreamAsync(Arg.Any<string>(), Arg.Any<IReadOnlyDictionary<string, string>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return await CreateStreamResultAsync(HttpStatusCode.OK, CreateBytes(8));
|
||||
}, callInfo.Arg<CancellationToken>()));
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(request, cancellationTokenSource.Token);
|
||||
await operationStarted.Task;
|
||||
cancellationTokenSource.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the upstream endpoint the segment request is expected to be sent to.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to build the endpoint for.</param>
|
||||
/// <returns>The expected upstream endpoint.</returns>
|
||||
private static string BuildExpectedEndpoint(StreamMusicTrackSegmentRequest request)
|
||||
{
|
||||
return ApiRoutes.Music.STREAM_TRACK_SEGMENT
|
||||
.Replace("{libraryId}", request.LibraryId.ToString())
|
||||
.Replace("{artistId}", request.ArtistId)
|
||||
.Replace("{albumId}", request.AlbumId)
|
||||
.Replace("{trackId}", request.TrackId)
|
||||
.Replace("{deliveryId}", request.DeliveryId)
|
||||
.Replace("{segmentIndex}", request.SegmentIndex.ToString(CultureInfo.InvariantCulture));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a streamed API response with a status code, a body and an optional media type.
|
||||
/// </summary>
|
||||
/// <param name="statusCode">The status code of the response.</param>
|
||||
/// <param name="contentBytes">The bytes of the content of the response.</param>
|
||||
/// <param name="contentType">The optional media type of the content.</param>
|
||||
/// <returns>The created streamed response.</returns>
|
||||
private static async Task<ApiStreamResult> CreateStreamResultAsync(HttpStatusCode statusCode, byte[] contentBytes, string? contentType = null)
|
||||
{
|
||||
HttpResponseMessage response = new(statusCode)
|
||||
{
|
||||
Content = new ByteArrayContent(contentBytes)
|
||||
};
|
||||
if (contentType is not null)
|
||||
response.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
|
||||
return await ApiStreamResult.CreateAsync(response, CancellationToken.None);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the bytes written to the response body of the provided HTTP context.
|
||||
/// </summary>
|
||||
/// <param name="httpContext">The HTTP context whose response body is read.</param>
|
||||
/// <returns>The bytes written to the response body.</returns>
|
||||
private static byte[] ReadResponseBody(HttpContext httpContext)
|
||||
{
|
||||
httpContext.Response.Body.Position = 0;
|
||||
using MemoryStream writtenBody = new();
|
||||
httpContext.Response.Body.CopyTo(writtenBody);
|
||||
return writtenBody.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a deterministic byte array that stands in for the content of a segment.
|
||||
/// </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))];
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user