mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 07: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
+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