mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-02 16: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
+73
@@ -7,6 +7,7 @@ using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Playback
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Playback;
|
||||
using Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetPlaybackManifest;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
@@ -96,6 +97,8 @@ public class GetPlaybackManifestEndpointTests : IClassFixture<AuthenticatedLumin
|
||||
Assert.True(manifest.IsSeekable);
|
||||
Assert.Equal($"/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream", manifest.StreamPath);
|
||||
Assert.DoesNotContain("http", manifest.StreamPath, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Null(manifest.DeliveryId);
|
||||
Assert.Null(manifest.SegmentStreamPathTemplate);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -119,6 +122,59 @@ public class GetPlaybackManifestEndpointTests : IClassFixture<AuthenticatedLumin
|
||||
Assert.Equal(PlaybackDeliveryShape.TimeAddressedSegments, manifest.DeliveryShape);
|
||||
Assert.Equal(6, manifest.SegmentDurationSeconds);
|
||||
Assert.True(manifest.IsSeekable);
|
||||
Assert.NotNull(manifest.DeliveryId);
|
||||
Assert.Matches("^[0-9a-f]{32}$", manifest.DeliveryId);
|
||||
Assert.Equal(BuildExpectedSegmentStreamPathTemplate(libraryId, artistId, albumId, trackId), manifest.SegmentStreamPathTemplate);
|
||||
Assert.DoesNotContain("http", manifest.SegmentStreamPathTemplate, StringComparison.OrdinalIgnoreCase);
|
||||
string cacheControl = string.Join(", ", response.Headers.GetValues("Cache-Control"));
|
||||
Assert.Contains("private", cacheControl);
|
||||
Assert.Contains("no-store", cacheControl);
|
||||
Assert.Contains("Authorization", response.Headers.Vary);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaybackManifest_WhenTheSameTrackIsRequestedTwice_ShouldReuseTheSameDeliveryId()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, container: "OGG", audioCodec: "OPUS");
|
||||
string requestPath = $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/playback-manifest?capabilities=mp3/mp3";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage firstResponse = await _client.GetAsync(requestPath);
|
||||
HttpResponseMessage secondResponse = await _client.GetAsync(requestPath);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, firstResponse.StatusCode);
|
||||
Assert.Equal(HttpStatusCode.OK, secondResponse.StatusCode);
|
||||
PlaybackManifestResponse? firstManifest = await ReadManifestAsync(firstResponse);
|
||||
PlaybackManifestResponse? secondManifest = await ReadManifestAsync(secondResponse);
|
||||
Assert.NotNull(firstManifest);
|
||||
Assert.NotNull(secondManifest);
|
||||
Assert.NotNull(firstManifest!.DeliveryId);
|
||||
Assert.Equal(firstManifest.DeliveryId, secondManifest!.DeliveryId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaybackManifest_WhenTheTranscodedResponseIsReread_ShouldKeepAWellFormedDeliveryId()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, container: "OGG", audioCodec: "OPUS");
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/playback-manifest?capabilities=mp3/mp3");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Act
|
||||
using JsonDocument firstRead = JsonDocument.Parse(content);
|
||||
string? deliveryIdFromFirstRead = firstRead.RootElement.GetProperty("deliveryId").GetString();
|
||||
PlaybackManifestResponse? secondRead = JsonSerializer.Deserialize<PlaybackManifestResponse>(content, _jsonOptions);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(deliveryIdFromFirstRead);
|
||||
Assert.Matches("^[0-9a-f]{32}$", deliveryIdFromFirstRead);
|
||||
Assert.NotNull(secondRead);
|
||||
Assert.Equal(deliveryIdFromFirstRead, secondRead!.DeliveryId);
|
||||
Assert.Matches("^[0-9a-f]{32}$", secondRead.DeliveryId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -230,6 +286,23 @@ public class GetPlaybackManifestEndpointTests : IClassFixture<AuthenticatedLumin
|
||||
return (userId, username);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the segment stream path template the manifest is expected to report for a track.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the track belongs to.</param>
|
||||
/// <param name="artistId">The Id of the artist the album belongs to.</param>
|
||||
/// <param name="albumId">The Id of the album the track belongs to.</param>
|
||||
/// <param name="trackId">The Id of the track.</param>
|
||||
/// <returns>The expected segment stream path template, with its placeholders preserved.</returns>
|
||||
private static string BuildExpectedSegmentStreamPathTemplate(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)
|
||||
{
|
||||
return ApiRoutes.Tracks.STREAM_TRACK_SEGMENT
|
||||
.Replace("{libraryId}", libraryId.ToString())
|
||||
.Replace("{artistId}", artistId.ToString())
|
||||
.Replace("{albumId}", albumId.ToString())
|
||||
.Replace("{trackId}", trackId.ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the playback manifest of a response.
|
||||
/// </summary>
|
||||
|
||||
+368
@@ -0,0 +1,368 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetTrackSegment;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
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.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetTrackSegment;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetTrackSegmentEndpoint"/> class.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The successful production path of a segment is not exercised here, because it requires ffmpeg, which is not part of the test environment. Every
|
||||
/// covered case is rejected before the normalization pipeline is entered, so these tests are deterministic and environment independent.
|
||||
/// </remarks>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetTrackSegmentEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly string _contentRootPath = Path.Combine(Path.GetTempPath(), $"lumina-track-segment-tests-{Guid.NewGuid():N}");
|
||||
private readonly List<string> _temporaryFiles = [];
|
||||
private readonly List<Guid> _seededLibraryIds = [];
|
||||
private readonly List<Guid> _seededArtistIds = [];
|
||||
private readonly List<Guid> _seededAlbumIds = [];
|
||||
private readonly List<Guid> _seededTrackIds = [];
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter() }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetTrackSegmentEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetTrackSegmentEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the authenticated API client and the temporary content root of the test.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
Directory.CreateDirectory(_contentRootPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTrackSegment_WhenUnauthorized_ShouldReturnUnauthorizedResultWithoutLeakingTheDeliveryHandle()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string trackPath = WriteContentFile("bohemian-rhapsody.ogg", CreateAudioBytes());
|
||||
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, trackPath);
|
||||
string deliveryId = await GetDeliveryIdAsync(libraryId, artistId, albumId, trackId);
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync(BuildSegmentPath(libraryId, artistId, albumId, trackId, deliveryId, 0));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
// The request path is echoed by the problem details, so the handle the caller sent appears there; no other handle may be disclosed.
|
||||
string[] disclosedHandleCandidates = [.. System.Text.RegularExpressions.Regex.Matches(content, "[0-9a-f]{32}").Select(match => match.Value)];
|
||||
Assert.All(disclosedHandleCandidates, candidate => Assert.Equal(deliveryId, candidate));
|
||||
}
|
||||
|
||||
[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
|
||||
public async Task GetTrackSegment_WhenDeliveryIdFormatIsInvalid_ShouldReturnValidationProblem(string malformedHandleKind)
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string trackPath = WriteContentFile("love-of-my-life.ogg", CreateAudioBytes());
|
||||
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, trackPath);
|
||||
string validDeliveryId = await GetDeliveryIdAsync(libraryId, artistId, albumId, trackId);
|
||||
string malformedDeliveryId = malformedHandleKind switch
|
||||
{
|
||||
"uppercase" => validDeliveryId.ToUpperInvariant(),
|
||||
_ => Guid.Parse(validDeliveryId).ToString("D"),
|
||||
};
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(BuildSegmentPath(libraryId, artistId, albumId, trackId, malformedDeliveryId, 0));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase);
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails.RootElement.GetProperty("detail").GetString());
|
||||
Assert.Contains(
|
||||
"DeliveryIdIsInvalid",
|
||||
problemDetails.RootElement.GetProperty("errors").GetProperty("General.Validation").EnumerateArray().Select(error => error.GetString()));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTrackSegment_WhenDeliveryIdIsUnknown_ShouldReturnPlaybackDeliveryNotFound()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string trackPath = WriteContentFile("you-re-my-best-friend.ogg", CreateAudioBytes());
|
||||
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, trackPath);
|
||||
string unknownDeliveryId = Guid.NewGuid().ToString("N");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(BuildSegmentPath(libraryId, artistId, albumId, trackId, unknownDeliveryId, 0));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails? problemDetails = await ReadProblemDetailsAsync(response);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal("General.NotFound", problemDetails!.Title);
|
||||
Assert.Equal("PlaybackDeliveryNotFound", problemDetails.Detail);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("library")] // the handle was issued for the library of another delivery
|
||||
[InlineData("artist")] // the handle was issued for the artist of another delivery
|
||||
[InlineData("album")] // the handle was issued for the album of another delivery
|
||||
public async Task GetTrackSegment_WhenDeliveryWasIssuedForAnotherScope_ShouldReturnPlaybackDeliveryNotFound(string mismatchedScope)
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string trackPath = WriteContentFile("news-of-the-world.ogg", CreateAudioBytes());
|
||||
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, trackPath);
|
||||
string deliveryId = await GetDeliveryIdAsync(libraryId, artistId, albumId, trackId);
|
||||
// A second library owned by the same user keeps the ownership check passing, so the delivery scope is what rejects the request.
|
||||
Guid otherLibraryId = await SeedLibraryAsync(userId);
|
||||
Guid requestedLibraryId = mismatchedScope == "library" ? otherLibraryId : libraryId;
|
||||
Guid requestedArtistId = mismatchedScope == "artist" ? Guid.NewGuid() : artistId;
|
||||
Guid requestedAlbumId = mismatchedScope == "album" ? Guid.NewGuid() : albumId;
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(BuildSegmentPath(requestedLibraryId, requestedArtistId, requestedAlbumId, trackId, deliveryId, 0));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails? problemDetails = await ReadProblemDetailsAsync(response);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal("General.NotFound", problemDetails!.Title);
|
||||
Assert.Equal("PlaybackDeliveryNotFound", problemDetails.Detail);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTrackSegment_WhenTrackFileIsOutsideTheLibraryContentLocations_ShouldReturnTrackFileNotFoundWithoutLeakingThePath()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string outsideFilePath = Path.Combine(Path.GetTempPath(), $"lumina-track-segment-outside-{Guid.NewGuid():N}.ogg");
|
||||
await File.WriteAllBytesAsync(outsideFilePath, CreateAudioBytes());
|
||||
_temporaryFiles.Add(outsideFilePath);
|
||||
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, outsideFilePath);
|
||||
string deliveryId = await GetDeliveryIdAsync(libraryId, artistId, albumId, trackId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(BuildSegmentPath(libraryId, artistId, albumId, trackId, deliveryId, 0));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain(outsideFilePath, content, StringComparison.OrdinalIgnoreCase);
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails? problemDetails = JsonSerializer.Deserialize<Microsoft.AspNetCore.Mvc.ProblemDetails>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal("General.NotFound", problemDetails!.Title);
|
||||
Assert.Equal("TrackFileNotFound", problemDetails.Detail);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a library owned by <paramref name="userId"/>, an artist of that library, an album of that artist and a track of that album.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="trackPath">The file system path of the audio file of the track.</param>
|
||||
/// <returns>The Ids of the seeded library, artist, album and track.</returns>
|
||||
private async Task<(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)> SeedLibraryArtistAlbumAndTrackAsync(Guid userId, string trackPath)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: [_contentRootPath]));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen"));
|
||||
dbContext.Albums.Add(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "A Night at the Opera"));
|
||||
dbContext.Tracks.Add(_trackEntityFixture.Create(
|
||||
id: trackId,
|
||||
albumId: albumId,
|
||||
libraryId: libraryId,
|
||||
path: trackPath,
|
||||
container: "OGG",
|
||||
audioCodec: "OPUS",
|
||||
title: "A Track",
|
||||
includeMetadata: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededLibraryIds.Add(libraryId);
|
||||
_seededArtistIds.Add(artistId);
|
||||
_seededAlbumIds.Add(albumId);
|
||||
_seededTrackIds.Add(trackId);
|
||||
return (libraryId, artistId, albumId, trackId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an additional music library owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Reissues", libraryType: LibraryType.Music, contentLocations: [_contentRootPath]));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededLibraryIds.Add(libraryId);
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Requests a transcoded playback manifest for the seeded track and returns the delivery handle it reports.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the track belongs to.</param>
|
||||
/// <param name="artistId">The Id of the artist the album belongs to.</param>
|
||||
/// <param name="albumId">The Id of the album the track belongs to.</param>
|
||||
/// <param name="trackId">The Id of the track.</param>
|
||||
/// <returns>The delivery handle of the normalized delivery.</returns>
|
||||
private async Task<string> GetDeliveryIdAsync(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)
|
||||
{
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/playback-manifest?capabilities=mp3/mp3");
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
PlaybackManifestResponse? manifest = JsonSerializer.Deserialize<PlaybackManifestResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(manifest);
|
||||
Assert.NotNull(manifest!.DeliveryId);
|
||||
return manifest.DeliveryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the route of a single segment of the normalized audio of a track.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the track belongs to.</param>
|
||||
/// <param name="artistId">The Id of the artist the album belongs to.</param>
|
||||
/// <param name="albumId">The Id of the album the track belongs to.</param>
|
||||
/// <param name="trackId">The Id of the track.</param>
|
||||
/// <param name="deliveryId">The opaque handle of the normalized delivery.</param>
|
||||
/// <param name="segmentIndex">The zero based index of the segment.</param>
|
||||
/// <returns>The route of the requested segment.</returns>
|
||||
private static string BuildSegmentPath(Guid libraryId, Guid artistId, Guid albumId, Guid trackId, string deliveryId, int segmentIndex)
|
||||
{
|
||||
return $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream/deliveries/{deliveryId}/segments/{segmentIndex}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes an audio file with the provided <paramref name="audioBytes"/> inside the content root of the test, and returns its full path.
|
||||
/// </summary>
|
||||
/// <param name="fileName">The name of the audio file to write.</param>
|
||||
/// <param name="audioBytes">The bytes of the audio file to write.</param>
|
||||
/// <returns>The full path of the written audio file.</returns>
|
||||
private string WriteContentFile(string fileName, byte[] audioBytes)
|
||||
{
|
||||
string filePath = Path.Combine(_contentRootPath, fileName);
|
||||
File.WriteAllBytes(filePath, audioBytes);
|
||||
return filePath;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a deterministic byte array that stands in for the content of an audio file.
|
||||
/// </summary>
|
||||
/// <returns>The created bytes.</returns>
|
||||
private static byte[] CreateAudioBytes()
|
||||
{
|
||||
return [.. Enumerable.Range(0, 4096).Select(index => (byte)(index % 256))];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the problem details of a response.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to read.</param>
|
||||
/// <returns>The deserialized problem details.</returns>
|
||||
private async Task<Microsoft.AspNetCore.Mvc.ProblemDetails?> ReadProblemDetailsAsync(HttpResponseMessage response)
|
||||
{
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
return JsonSerializer.Deserialize<Microsoft.AspNetCore.Mvc.ProblemDetails>(content, _jsonOptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the currently authenticated test user.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the authenticated test user.</returns>
|
||||
private Guid GetCurrentUserId()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
|
||||
return user.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Cleans up the seeded database rows, the temporary files and the test user of the test.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
using (IServiceScope scope = _apiFactory.Services.CreateScope())
|
||||
{
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
foreach (Guid trackId in _seededTrackIds)
|
||||
{
|
||||
TrackEntity? track = dbContext.Tracks.Find(trackId);
|
||||
if (track is not null)
|
||||
dbContext.Tracks.Remove(track);
|
||||
}
|
||||
foreach (Guid albumId in _seededAlbumIds)
|
||||
{
|
||||
AlbumEntity? album = dbContext.Albums.Find(albumId);
|
||||
if (album is not null)
|
||||
dbContext.Albums.Remove(album);
|
||||
}
|
||||
foreach (Guid artistId in _seededArtistIds)
|
||||
{
|
||||
ArtistEntity? artist = dbContext.Artists.Find(artistId);
|
||||
if (artist is not null)
|
||||
dbContext.Artists.Remove(artist);
|
||||
}
|
||||
foreach (Guid libraryId in _seededLibraryIds)
|
||||
{
|
||||
LibraryEntity? library = dbContext.Libraries.Find(libraryId);
|
||||
if (library is not null)
|
||||
dbContext.Libraries.Remove(library);
|
||||
}
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
if (Directory.Exists(_contentRootPath))
|
||||
Directory.Delete(_contentRootPath, recursive: true);
|
||||
foreach (string temporaryFile in _temporaryFiles)
|
||||
if (File.Exists(temporaryFile))
|
||||
File.Delete(temporaryFile);
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+15
-6
@@ -1,5 +1,4 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.HealthChecks;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Api;
|
||||
@@ -29,6 +28,11 @@ public class LuminaWebFactory : WebApplicationFactory<Program>, IDisposable
|
||||
/// </summary>
|
||||
public StubApiHttpClient ApiClientStub { get; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// Gets the stub used in place of the remote streaming API client.
|
||||
/// </summary>
|
||||
public StubStreamingApiHttpClient StreamingApiClientStub { get; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LuminaWebFactory"/> class.
|
||||
/// </summary>
|
||||
@@ -44,7 +48,7 @@ public class LuminaWebFactory : WebApplicationFactory<Program>, IDisposable
|
||||
{
|
||||
builder.ConfigureAppConfiguration((context, config) =>
|
||||
{
|
||||
// provide the application configuration values that the Web app validates on startup
|
||||
// Provide the application configuration values that the Web app validates on startup.
|
||||
config.AddInMemoryCollection(initialData: new Dictionary<string, string?>
|
||||
{
|
||||
["EncryptionSettings:SecretKey"] = TEST_ENCRYPTION_KEY,
|
||||
@@ -55,14 +59,19 @@ public class LuminaWebFactory : WebApplicationFactory<Program>, IDisposable
|
||||
});
|
||||
builder.ConfigureServices(services =>
|
||||
{
|
||||
// remove the typed HTTP client registration, so that the stub can take its place
|
||||
ServiceDescriptor[] apiClientDescriptors = services.Where(serviceDescriptor => serviceDescriptor.ServiceType == typeof(IApiHttpClient)).ToArray();
|
||||
// Remove the typed HTTP client registration, so that the stub can take its place.
|
||||
ServiceDescriptor[] apiClientDescriptors = [.. services.Where(serviceDescriptor => serviceDescriptor.ServiceType == typeof(IApiHttpClient))];
|
||||
foreach (ServiceDescriptor descriptor in apiClientDescriptors)
|
||||
services.Remove(descriptor);
|
||||
services.AddSingleton<IApiHttpClient>(ApiClientStub);
|
||||
|
||||
// the API reachability health check resolves ApiReachabilityHealthCheck from DI when it runs; replace its
|
||||
// registration with a healthy subclass, since no real API exists during these tests
|
||||
// Remove the typed streaming HTTP client registration, so that the streaming stub can take its place.
|
||||
ServiceDescriptor[] streamingApiClientDescriptors = [.. services.Where(serviceDescriptor => serviceDescriptor.ServiceType == typeof(IStreamingApiHttpClient))];
|
||||
foreach (ServiceDescriptor descriptor in streamingApiClientDescriptors)
|
||||
services.Remove(descriptor);
|
||||
services.AddSingleton<IStreamingApiHttpClient>(StreamingApiClientStub);
|
||||
|
||||
// The API reachability health check resolves ApiReachabilityHealthCheck from DI when it runs; replace its registration with a healthy subclass, since no real API exists during these tests.
|
||||
services.RemoveAll<ApiReachabilityHealthCheck>();
|
||||
services.AddScoped<ApiReachabilityHealthCheck, HealthyApiReachabilityHealthCheck>();
|
||||
});
|
||||
|
||||
+194
@@ -0,0 +1,194 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
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.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetPlaybackManifest;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetPlaybackManifestEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetPlaybackManifestEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private const string VALID_DELIVERY_ID = "0123456789abcdef0123456789abcdef";
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly PlaybackManifestDtoFixture _playbackManifestDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPlaybackManifestEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetPlaybackManifestEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaybackManifest_WhenManifestIsNotADirectPlay_ShouldReturnTheWebProxyPaths()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
PlaybackManifestDto manifest = _playbackManifestDtoFixture.Create(
|
||||
trackId: trackId,
|
||||
isDirectPlay: false,
|
||||
deliveryId: VALID_DELIVERY_ID,
|
||||
segmentStreamPathTemplate: "/api/v1/libraries/ancient/stream/deliveries/{deliveryId}/segments/{segmentIndex}");
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/playback-manifest", manifest);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = CreateGetRequest(libraryId, artistId, albumId, trackId);
|
||||
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
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
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.Contains("private", response.Headers.CacheControl?.ToString());
|
||||
Assert.Contains("no-store", response.Headers.CacheControl?.ToString());
|
||||
Assert.Contains("Cookie", response.Headers.Vary);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaybackManifest_WhenManifestIsADirectPlay_ShouldReturnNullDeliveryAndTemplate()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
PlaybackManifestDto manifest = _playbackManifestDtoFixture.Create(
|
||||
trackId: trackId,
|
||||
isDirectPlay: true,
|
||||
includeDeliveryId: false,
|
||||
includeSegmentStreamPathTemplate: false);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/playback-manifest", manifest);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = CreateGetRequest(libraryId, artistId, albumId, trackId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
JsonElement data = json.RootElement.GetProperty("data");
|
||||
Assert.Equal(JsonValueKind.Null, data.GetProperty("deliveryId").ValueKind);
|
||||
Assert.Equal(JsonValueKind.Null, data.GetProperty("segmentStreamPathTemplate").ValueKind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaybackManifest_WhenApiDeclaresATemplateWithAnInvalidDeliveryId_ShouldReturnBadGateway()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
PlaybackManifestDto manifest = _playbackManifestDtoFixture.Create(
|
||||
trackId: trackId,
|
||||
isDirectPlay: false,
|
||||
deliveryId: "not-a-valid-handle",
|
||||
segmentStreamPathTemplate: "/api/v1/libraries/ancient/stream/deliveries/{deliveryId}/segments/{segmentIndex}");
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/playback-manifest", manifest);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = CreateGetRequest(libraryId, artistId, albumId, trackId);
|
||||
// The player fetch classifies as a raw media request, which is answered with a bare status instead of a page or a JSON body.
|
||||
getRequest.Headers.Accept.Clear();
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("audio/mpeg"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadGateway, response.StatusCode);
|
||||
Assert.Equal(string.Empty, content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaybackManifest_WhenNotAuthenticated_ShouldRedirectToLoginWithoutCallingTheApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.GetAsync($"/en-us/library/audio-library/music-library/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/api-get-playback-manifest?libraryId={Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("libraries/", StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Tracks; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task GetPlaybackManifest_WithSQLInjectionInRouteId_ShouldNormalizeTheIdWithoutLeakingData(string maliciousId)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
string normalizedId = Guid.Empty.ToString();
|
||||
PlaybackManifestDto manifest = _playbackManifestDtoFixture.Create(isDirectPlay: true, includeDeliveryId: false, includeSegmentStreamPathTemplate: false);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/artists/{normalizedId}/albums/{normalizedId}/tracks/{normalizedId}/playback-manifest", manifest);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/audio-library/music-library/artists/{Uri.EscapeDataString(maliciousId)}/albums/{Uri.EscapeDataString(maliciousId)}/tracks/{Uri.EscapeDataString(maliciousId)}/api-get-playback-manifest?libraryId={libraryId}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using (JsonDocument json = JsonDocument.Parse(content))
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(maliciousId, content, StringComparison.Ordinal);
|
||||
Assert.Contains(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == $"libraries/{libraryId}/artists/{normalizedId}/albums/{normalizedId}/tracks/{normalizedId}/playback-manifest");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an authenticated JSON request for the playback manifest of a track.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the track belongs to.</param>
|
||||
/// <param name="artistId">The Id of the artist the album belongs to.</param>
|
||||
/// <param name="albumId">The Id of the album the track belongs to.</param>
|
||||
/// <param name="trackId">The Id of the track.</param>
|
||||
/// <returns>The configured request.</returns>
|
||||
private static HttpRequestMessage CreateGetRequest(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)
|
||||
{
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-get-playback-manifest?libraryId={libraryId}");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
return getRequest;
|
||||
}
|
||||
}
|
||||
+202
@@ -0,0 +1,202 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.StreamMusicTrackSegment;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Globalization;
|
||||
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.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.StreamMusicTrackSegment;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="StreamMusicTrackSegmentEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class StreamMusicTrackSegmentEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="StreamMusicTrackSegmentEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public StreamMusicTrackSegmentEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StreamMusicTrackSegment_WhenRequestIsValid_ShouldProxyTheApiSegment()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.StreamingApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
string deliveryId = Guid.NewGuid().ToString("N");
|
||||
const int SEGMENT_INDEX = 3;
|
||||
string expectedEndpoint = BuildExpectedEndpoint(libraryId, artistId, albumId, trackId, deliveryId, SEGMENT_INDEX);
|
||||
byte[] contentBytes = CreateBytes(1024);
|
||||
_apiFactory.StreamingApiClientStub.RegisterStreamResponse(expectedEndpoint, await CreateStreamResultAsync(contentBytes));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync(BuildBrowserPath(libraryId, artistId, albumId, trackId, deliveryId, SEGMENT_INDEX));
|
||||
byte[] responseBytes = await response.Content.ReadAsByteArrayAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.PartialContent, response.StatusCode);
|
||||
Assert.Equal("audio/mp4", response.Content.Headers.ContentType?.MediaType);
|
||||
Assert.Equal(contentBytes.Length, response.Content.Headers.ContentLength);
|
||||
Assert.Equal(contentBytes, responseBytes);
|
||||
Assert.Equal("9", response.Headers.GetValues(ApiStreamResult.SEGMENT_COUNT_HEADER_NAME).Single());
|
||||
Assert.Equal("6.5", response.Headers.GetValues(ApiStreamResult.SEGMENT_START_SECONDS_HEADER_NAME).Single());
|
||||
Assert.Equal("300", response.Headers.GetValues(ApiStreamResult.TRACK_DURATION_SECONDS_HEADER_NAME).Single());
|
||||
Assert.Contains("private", response.Headers.CacheControl?.ToString());
|
||||
Assert.DoesNotContain("public", response.Headers.CacheControl?.ToString());
|
||||
Assert.Contains("Cookie", response.Headers.Vary);
|
||||
Assert.Single(_apiFactory.StreamingApiClientStub.GetEndpointsCalled);
|
||||
Assert.Equal(expectedEndpoint, _apiFactory.StreamingApiClientStub.GetEndpointsCalled[0]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StreamMusicTrackSegment_WhenDeliveryIdIsInvalid_ShouldReturnNotFoundWithoutCallingTheApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.StreamingApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync(BuildBrowserPath(Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid().ToString("N").ToUpperInvariant(), 0));
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
Assert.Equal(string.Empty, content);
|
||||
Assert.Empty(_apiFactory.StreamingApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(HttpStatusCode.ServiceUnavailable)] // a busy normalization pipeline is a transient condition
|
||||
[InlineData(HttpStatusCode.TooManyRequests)] // the stream concurrency limit was reached
|
||||
public async Task StreamMusicTrackSegment_WhenApiReportsATransientCondition_ShouldReturnABareStatus(HttpStatusCode statusCode)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.StreamingApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
string deliveryId = Guid.NewGuid().ToString("N");
|
||||
string expectedEndpoint = BuildExpectedEndpoint(libraryId, artistId, albumId, trackId, deliveryId, 0);
|
||||
_apiFactory.StreamingApiClientStub.RegisterStreamException(expectedEndpoint, new ApiException(
|
||||
new ProblemDetailsDto { Title = "General.Failure", Detail = "InternalServerError", Status = (int)statusCode },
|
||||
statusCode,
|
||||
expectedEndpoint));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync(BuildBrowserPath(libraryId, artistId, albumId, trackId, deliveryId, 0));
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(statusCode, response.StatusCode);
|
||||
Assert.Equal(string.Empty, content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StreamMusicTrackSegment_WhenNotAuthenticated_ShouldRedirectToLoginWithoutCallingTheApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.StreamingApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.GetAsync(BuildBrowserPath(Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid().ToString("N"), 0));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Empty(_apiFactory.StreamingApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the browser facing route of a single segment of the normalized audio of a track.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the track belongs to.</param>
|
||||
/// <param name="artistId">The Id of the artist the album belongs to.</param>
|
||||
/// <param name="albumId">The Id of the album the track belongs to.</param>
|
||||
/// <param name="trackId">The Id of the track.</param>
|
||||
/// <param name="deliveryId">The opaque handle of the normalized delivery.</param>
|
||||
/// <param name="segmentIndex">The zero based index of the segment.</param>
|
||||
/// <returns>The browser facing route of the requested segment.</returns>
|
||||
private static string BuildBrowserPath(Guid libraryId, Guid artistId, Guid albumId, Guid trackId, string deliveryId, int segmentIndex)
|
||||
{
|
||||
return $"/en-us/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-stream-track-segment/{deliveryId}/{segmentIndex}?libraryId={libraryId}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the upstream endpoint the segment request is expected to be sent to.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the track belongs to.</param>
|
||||
/// <param name="artistId">The Id of the artist the album belongs to.</param>
|
||||
/// <param name="albumId">The Id of the album the track belongs to.</param>
|
||||
/// <param name="trackId">The Id of the track.</param>
|
||||
/// <param name="deliveryId">The opaque handle of the normalized delivery.</param>
|
||||
/// <param name="segmentIndex">The zero based index of the segment.</param>
|
||||
/// <returns>The expected upstream endpoint.</returns>
|
||||
private static string BuildExpectedEndpoint(Guid libraryId, Guid artistId, Guid albumId, Guid trackId, string deliveryId, int segmentIndex)
|
||||
{
|
||||
return ApiRoutes.Music.STREAM_TRACK_SEGMENT
|
||||
.Replace("{libraryId}", libraryId.ToString())
|
||||
.Replace("{artistId}", artistId.ToString())
|
||||
.Replace("{albumId}", albumId.ToString())
|
||||
.Replace("{trackId}", trackId.ToString())
|
||||
.Replace("{deliveryId}", deliveryId)
|
||||
.Replace("{segmentIndex}", segmentIndex.ToString(CultureInfo.InvariantCulture));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a streamed API response with a partial content status, a body and the segment headers.
|
||||
/// </summary>
|
||||
/// <param name="contentBytes">The bytes of the content of the response.</param>
|
||||
/// <returns>The created streamed response.</returns>
|
||||
private static async Task<ApiStreamResult> CreateStreamResultAsync(byte[] contentBytes)
|
||||
{
|
||||
HttpResponseMessage response = new(HttpStatusCode.PartialContent)
|
||||
{
|
||||
Content = new ByteArrayContent(contentBytes)
|
||||
};
|
||||
response.Content.Headers.ContentType = new MediaTypeHeaderValue("audio/mp4");
|
||||
response.Headers.CacheControl = new CacheControlHeaderValue { Public = true, MaxAge = TimeSpan.FromSeconds(60) };
|
||||
response.Headers.TryAddWithoutValidation(ApiStreamResult.SEGMENT_COUNT_HEADER_NAME, "9");
|
||||
response.Headers.TryAddWithoutValidation(ApiStreamResult.SEGMENT_START_SECONDS_HEADER_NAME, "6.5");
|
||||
response.Headers.TryAddWithoutValidation(ApiStreamResult.TRACK_DURATION_SECONDS_HEADER_NAME, "300");
|
||||
return await ApiStreamResult.CreateAsync(response, CancellationToken.None);
|
||||
}
|
||||
|
||||
/// <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