Implements tests for commit 45f9aa3bd5

This commit is contained in:
BinaryAlley committed 2026-10-28 22:34:32 +02:00
1 parent d61a114d80
commit aeefa9487e
44 files changed
+6929 -18

No files matched your search

@@ -0,0 +1,75 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using Lumina.Domain.SharedKernel.Common.Enums.Playback;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
/// <summary>
/// Fixture class for the <see cref="NormalizedTrackDto"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class NormalizedTrackDtoFixture
{
private readonly Faker _faker = new();
private readonly NormalizedTrackSegmentDtoFixture _normalizedTrackSegmentDtoFixture = new();
/// <summary>
/// Creates a random valid <see cref="NormalizedTrackDto"/>.
/// </summary>
/// <param name="trackId">Optional. The Id of the track whose audio the cached entry holds.</param>
/// <param name="cacheId">Optional. The opaque identifier of the cached entry that holds the normalized audio.</param>
/// <param name="mode">Optional. The way the audio is delivered.</param>
/// <param name="container">Optional. The container of the delivered audio.</param>
/// <param name="codec">Optional. The codec of the delivered audio.</param>
/// <param name="segmentDurationSeconds">Optional. The duration of each segment of the delivered audio, in seconds.</param>
/// <param name="durationInSeconds">Optional. The duration of the produced and cached audio, in seconds.</param>
/// <param name="segments">Optional. The segments that make up the delivered audio, in playback order.</param>
/// <param name="includeSegments">Whether the segments should be included, or forced to an empty collection.</param>
/// <returns>The created <see cref="NormalizedTrackDto"/>.</returns>
public NormalizedTrackDto Create(
Guid? trackId = null,
string? cacheId = null,
PlaybackDeliveryMode? mode = null,
string? container = null,
string? codec = null,
int? segmentDurationSeconds = null,
int? durationInSeconds = null,
IReadOnlyList<NormalizedTrackSegmentDto>? segments = null,
bool includeSegments = true)
{
int resolvedSegmentDurationSeconds = segmentDurationSeconds ?? _faker.Random.Int(1, 30);
List<NormalizedTrackSegmentDto> generatedSegments = [];
int generatedSegmentCount = _faker.Random.Int(1, 6);
for (int index = 0; index < generatedSegmentCount; index++)
generatedSegments.Add(_normalizedTrackSegmentDtoFixture.Create(
index: index,
startSeconds: index * resolvedSegmentDurationSeconds,
durationSeconds: resolvedSegmentDurationSeconds));
return new NormalizedTrackDto(
trackId ?? _faker.Random.Guid(),
cacheId ?? _faker.Random.Guid().ToString("N") + _faker.Random.Guid().ToString("N"),
mode ?? _faker.PickRandom(PlaybackDeliveryMode.Remux, PlaybackDeliveryMode.Transcode),
container ?? _faker.PickRandom("MP3", "AAC", "FLAC", "WAV", "OGG"),
codec ?? _faker.PickRandom("MP3", "AAC", "FLAC", "PCM", "OPUS"),
resolvedSegmentDurationSeconds,
durationInSeconds ?? _faker.Random.Int(1, 3600),
includeSegments ? (segments ?? generatedSegments) : []);
}
/// <summary>
/// Creates a list of <see cref="NormalizedTrackDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="NormalizedTrackDto"/> instances.</returns>
public List<NormalizedTrackDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,102 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using Lumina.Domain.SharedKernel.Common.Enums.Playback;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
#endregion
namespace Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
/// <summary>
/// Fixture class for the <see cref="NormalizedTrackRequestDto"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class NormalizedTrackRequestDtoFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="NormalizedTrackRequestDto"/>.
/// </summary>
/// <param name="trackId">Optional. The Id of the track whose audio is normalized.</param>
/// <param name="userId">Optional. The Id of the user whose request starts the production.</param>
/// <param name="sourcePath">Optional. The file system path of the stored audio file of the track.</param>
/// <param name="allowedRoots">Optional. The content locations the source path is allowed to be inside.</param>
/// <param name="sourceContainer">Optional. The container of the stored audio file, as captured by the probe.</param>
/// <param name="mode">Optional. The way the audio is delivered.</param>
/// <param name="container">Optional. The container of the delivered audio.</param>
/// <param name="codec">Optional. The codec of the delivered audio.</param>
/// <param name="segmentDurationSeconds">Optional. The duration of each segment of the delivered audio, in seconds.</param>
/// <param name="durationInSeconds">Optional. The duration of the audio of the track, in seconds.</param>
/// <param name="bitrate">Optional. The stored audio bitrate of the track, in kbps.</param>
/// <param name="sampleRate">Optional. The sample rate of the stored audio of the track, in Hz.</param>
/// <param name="channels">Optional. The number of audio channels of the track.</param>
/// <param name="bitDepth">Optional. The bit depth of the stored audio of the track.</param>
/// <param name="quality">Optional. The quality cap applied to the delivered audio when it has to be re-encoded.</param>
/// <param name="sourceLength">Optional. The length the source file had when the delivery was declared, in bytes.</param>
/// <param name="sourceLastModifiedUtc">Optional. The last modification time the source file had when the delivery was declared.</param>
/// <param name="includeSourceContainer">Whether the source container should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeBitrate">Whether the bitrate should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeBitDepth">Whether the bit depth should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="NormalizedTrackRequestDto"/>.</returns>
public NormalizedTrackRequestDto Create(
Guid? trackId = null,
Guid? userId = null,
string? sourcePath = null,
IReadOnlyList<string>? allowedRoots = null,
string? sourceContainer = null,
PlaybackDeliveryMode? mode = null,
string? container = null,
string? codec = null,
int? segmentDurationSeconds = null,
int? durationInSeconds = null,
int? bitrate = null,
int? sampleRate = null,
int? channels = null,
int? bitDepth = null,
PlaybackStreamingQuality? quality = null,
long? sourceLength = null,
DateTime? sourceLastModifiedUtc = null,
bool includeSourceContainer = true,
bool includeBitrate = true,
bool includeBitDepth = true)
{
IReadOnlyList<string> resolvedAllowedRoots = allowedRoots ?? [Path.Combine(Path.GetTempPath(), "lumina-tests", _faker.Random.AlphaNumeric(12))];
string resolvedSourcePath = sourcePath ?? (resolvedAllowedRoots.Count > 0
? Path.Combine(resolvedAllowedRoots[0], "track-" + _faker.Random.AlphaNumeric(8) + ".flac")
: Path.Combine(Path.GetTempPath(), "track-" + _faker.Random.AlphaNumeric(8) + ".flac"));
return new NormalizedTrackRequestDto(
trackId ?? _faker.Random.Guid(),
userId ?? _faker.Random.Guid(),
resolvedSourcePath,
resolvedAllowedRoots,
includeSourceContainer ? (sourceContainer ?? _faker.PickRandom("FLAC", "MP3", "OGG", "MP4", "WAV")) : null,
mode ?? _faker.PickRandom(PlaybackDeliveryMode.Remux, PlaybackDeliveryMode.Transcode),
container ?? _faker.PickRandom("MP3", "AAC", "FLAC", "WAV", "OGG"),
codec ?? _faker.PickRandom("MP3", "AAC", "FLAC", "PCM", "OPUS"),
segmentDurationSeconds ?? _faker.Random.Int(1, 30),
durationInSeconds ?? _faker.Random.Int(1, 3600),
includeBitrate ? (bitrate ?? _faker.Random.Int(96, 1411)) : null,
sampleRate ?? _faker.PickRandom(44100, 48000, 96000),
channels ?? _faker.PickRandom(1, 2, 6),
includeBitDepth ? (bitDepth ?? _faker.Random.Int(16, 24)) : null,
quality ?? _faker.PickRandom<PlaybackStreamingQuality>(),
sourceLength ?? _faker.Random.Long(1, 100_000_000),
sourceLastModifiedUtc ?? _faker.Date.Past().ToUniversalTime());
}
/// <summary>
/// Creates a list of <see cref="NormalizedTrackRequestDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="NormalizedTrackRequestDto"/> instances.</returns>
public List<NormalizedTrackRequestDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,56 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
#endregion
namespace Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
/// <summary>
/// Fixture class for the <see cref="NormalizedTrackSegmentDataDto"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class NormalizedTrackSegmentDataDtoFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="NormalizedTrackSegmentDataDto"/>.
/// </summary>
/// <param name="content">Optional. The read stream over the segment. When it is not supplied, a fresh empty <see cref="MemoryStream"/> is created.</param>
/// <param name="length">Optional. The length of the segment, in bytes.</param>
/// <param name="startSeconds">Optional. The exact start of the segment on the track timeline, in seconds.</param>
/// <param name="container">Optional. The container of the delivered audio.</param>
/// <param name="segmentCount">Optional. The number of segments the production holds.</param>
/// <param name="durationInSeconds">Optional. The duration of the produced normalized audio, in seconds.</param>
/// <returns>The created <see cref="NormalizedTrackSegmentDataDto"/>.</returns>
public NormalizedTrackSegmentDataDto Create(
Stream? content = null,
long? length = null,
decimal? startSeconds = null,
string? container = null,
int? segmentCount = null,
int? durationInSeconds = null)
{
return new NormalizedTrackSegmentDataDto(
content ?? new MemoryStream(),
length ?? _faker.Random.Long(1, 10_000_000),
startSeconds ?? _faker.Random.Decimal(0, 3600),
container ?? _faker.PickRandom("MP3", "AAC", "FLAC", "WAV", "OGG"),
segmentCount ?? _faker.Random.Int(1, 1000),
durationInSeconds ?? _faker.Random.Int(1, 3600));
}
/// <summary>
/// Creates a list of <see cref="NormalizedTrackSegmentDataDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="NormalizedTrackSegmentDataDto"/> instances.</returns>
public List<NormalizedTrackSegmentDataDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,49 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
/// <summary>
/// Fixture class for the <see cref="NormalizedTrackSegmentDto"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class NormalizedTrackSegmentDtoFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="NormalizedTrackSegmentDto"/>.
/// </summary>
/// <param name="index">Optional. The zero based position of the segment in the delivered audio.</param>
/// <param name="startSeconds">Optional. The time, in seconds from the start of the track, at which the segment starts.</param>
/// <param name="durationSeconds">Optional. The duration of the segment, in seconds.</param>
/// <param name="length">Optional. The length of the segment, in bytes.</param>
/// <returns>The created <see cref="NormalizedTrackSegmentDto"/>.</returns>
public NormalizedTrackSegmentDto Create(
int? index = null,
decimal? startSeconds = null,
decimal? durationSeconds = null,
long? length = null)
{
return new NormalizedTrackSegmentDto(
index ?? _faker.Random.Int(0, 1000),
startSeconds ?? _faker.Random.Decimal(0, 3600),
durationSeconds ?? _faker.Random.Decimal(1, 30),
length ?? _faker.Random.Long(1, 10_000_000));
}
/// <summary>
/// Creates a list of <see cref="NormalizedTrackSegmentDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="NormalizedTrackSegmentDto"/> instances.</returns>
public List<NormalizedTrackSegmentDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,54 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using Lumina.Domain.SharedKernel.Common.Enums.Playback;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
/// <summary>
/// Fixture class for the <see cref="PlaybackDeliveryDecisionDto"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class PlaybackDeliveryDecisionDtoFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="PlaybackDeliveryDecisionDto"/>.
/// </summary>
/// <param name="mode">Optional. The way the audio is delivered.</param>
/// <param name="container">Optional. The container of the delivered audio.</param>
/// <param name="codec">Optional. The codec of the delivered audio.</param>
/// <param name="shape">Optional. The shape the delivered audio is addressed and seeked by.</param>
/// <param name="segmentDurationSeconds">Optional. The duration of each segment of the delivered audio, in seconds.</param>
/// <returns>The created <see cref="PlaybackDeliveryDecisionDto"/>.</returns>
public PlaybackDeliveryDecisionDto Create(
PlaybackDeliveryMode? mode = null,
string? container = null,
string? codec = null,
PlaybackDeliveryShape? shape = null,
int? segmentDurationSeconds = null)
{
PlaybackDeliveryShape resolvedShape = shape ?? _faker.PickRandom<PlaybackDeliveryShape>();
return new PlaybackDeliveryDecisionDto(
mode ?? _faker.PickRandom(PlaybackDeliveryMode.Remux, PlaybackDeliveryMode.Transcode),
container ?? _faker.PickRandom("MP3", "AAC", "FLAC", "WAV", "OGG"),
codec ?? _faker.PickRandom("MP3", "AAC", "FLAC", "PCM", "OPUS"),
resolvedShape,
segmentDurationSeconds ?? (resolvedShape == PlaybackDeliveryShape.TimeAddressedSegments ? _faker.Random.Int(1, 30) : 0));
}
/// <summary>
/// Creates a list of <see cref="PlaybackDeliveryDecisionDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="PlaybackDeliveryDecisionDto"/> instances.</returns>
public List<PlaybackDeliveryDecisionDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,55 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using Lumina.Domain.SharedKernel.Common.Enums.Playback;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
/// <summary>
/// Fixture class for the <see cref="PlaybackDeliveryHandleDto"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class PlaybackDeliveryHandleDtoFixture
{
private readonly Faker _faker = new();
private readonly NormalizedTrackRequestDtoFixture _normalizedTrackRequestDtoFixture = new();
/// <summary>
/// Creates a random valid <see cref="PlaybackDeliveryHandleDto"/>.
/// </summary>
/// <param name="request">Optional. The complete normalization request the delivery declares.</param>
/// <param name="shape">Optional. The shape the delivered audio is addressed by.</param>
/// <param name="libraryId">Optional. The Id of the library the track belongs to.</param>
/// <param name="albumId">Optional. The Id of the album the track belongs to.</param>
/// <param name="artistId">Optional. The Id of the artist that owns the album.</param>
/// <returns>The created <see cref="PlaybackDeliveryHandleDto"/>.</returns>
public PlaybackDeliveryHandleDto Create(
NormalizedTrackRequestDto? request = null,
PlaybackDeliveryShape? shape = null,
Guid? libraryId = null,
Guid? albumId = null,
Guid? artistId = null)
{
return new PlaybackDeliveryHandleDto(
request ?? _normalizedTrackRequestDtoFixture.Create(),
shape ?? _faker.PickRandom<PlaybackDeliveryShape>(),
libraryId ?? _faker.Random.Guid(),
albumId ?? _faker.Random.Guid(),
artistId ?? _faker.Random.Guid());
}
/// <summary>
/// Creates a list of <see cref="PlaybackDeliveryHandleDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="PlaybackDeliveryHandleDto"/> instances.</returns>
public List<PlaybackDeliveryHandleDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,84 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
#endregion
namespace Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
/// <summary>
/// Fixture class for the <see cref="TrackPlaybackManifestDto"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class TrackPlaybackManifestDtoFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="TrackPlaybackManifestDto"/>.
/// </summary>
/// <param name="path">Optional. The file system path of the stored audio file of the track.</param>
/// <param name="container">Optional. The container of the audio file of the track.</param>
/// <param name="audioCodec">Optional. The audio codec used by the audio file of the track.</param>
/// <param name="durationInSeconds">Optional. The duration of the audio of the track, in seconds.</param>
/// <param name="sampleRate">Optional. The sample rate of the audio of the track, in Hz.</param>
/// <param name="channels">Optional. The number of audio channels of the track.</param>
/// <param name="bitDepth">Optional. The bit depth of the audio of the track.</param>
/// <param name="bitrate">Optional. The bitrate of the audio of the track, in kbps.</param>
/// <param name="replayGainTrackGain">Optional. The ReplayGain track gain of the track, in decibels.</param>
/// <param name="replayGainTrackPeak">Optional. The ReplayGain track peak of the track.</param>
/// <param name="replayGainAlbumGain">Optional. The ReplayGain album gain of the track, in decibels.</param>
/// <param name="replayGainAlbumPeak">Optional. The ReplayGain album peak of the track.</param>
/// <param name="includeContainer">Whether the container should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeAudioCodec">Whether the audio codec should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeBitDepth">Whether the bit depth should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeBitrate">Whether the bitrate should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeReplayGain">Whether the ReplayGain values should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="TrackPlaybackManifestDto"/>.</returns>
public TrackPlaybackManifestDto Create(
string? path = null,
string? container = null,
string? audioCodec = null,
int? durationInSeconds = null,
int? sampleRate = null,
int? channels = null,
int? bitDepth = null,
int? bitrate = null,
decimal? replayGainTrackGain = null,
decimal? replayGainTrackPeak = null,
decimal? replayGainAlbumGain = null,
decimal? replayGainAlbumPeak = null,
bool includeContainer = true,
bool includeAudioCodec = true,
bool includeBitDepth = true,
bool includeBitrate = true,
bool includeReplayGain = true)
{
return new TrackPlaybackManifestDto(
path ?? Path.Combine(_faker.System.DirectoryPath(), _faker.System.FileName("flac")),
includeContainer ? (container ?? _faker.PickRandom("FLAC", "MP3", "OGG", "MP4", "AAC", "WAV")) : null,
includeAudioCodec ? (audioCodec ?? _faker.PickRandom("FLAC", "MP3", "AAC", "ALAC", "PCM")) : null,
durationInSeconds ?? _faker.Random.Int(1, 3600),
sampleRate ?? _faker.PickRandom(44100, 48000, 96000),
channels ?? _faker.PickRandom(1, 2, 6),
includeBitDepth ? (bitDepth ?? _faker.Random.Int(8, 32)) : null,
includeBitrate ? (bitrate ?? _faker.Random.Int(96, 1411)) : null,
includeReplayGain ? (replayGainTrackGain ?? _faker.Random.Decimal(-20m, 0m)) : null,
includeReplayGain ? (replayGainTrackPeak ?? _faker.Random.Decimal(0m, 1.5m)) : null,
includeReplayGain ? (replayGainAlbumGain ?? _faker.Random.Decimal(-20m, 0m)) : null,
includeReplayGain ? (replayGainAlbumPeak ?? _faker.Random.Decimal(0m, 1.5m)) : null);
}
/// <summary>
/// Creates a list of <see cref="TrackPlaybackManifestDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="TrackPlaybackManifestDto"/> instances.</returns>
public List<TrackPlaybackManifestDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,69 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetPlaybackManifest;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetPlaybackManifest;
/// <summary>
/// Fixture class for the <see cref="GetPlaybackManifestQuery"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetPlaybackManifestQueryFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid query to get the playback manifest of a track.
/// </summary>
/// <param name="libraryId">Optional. The Id of the media library the track belongs to.</param>
/// <param name="artistId">Optional. The Id of the artist the album of the track belongs to.</param>
/// <param name="albumId">Optional. The Id of the album the track belongs to.</param>
/// <param name="trackId">Optional. The Id of the track whose playback manifest is retrieved.</param>
/// <param name="capabilities">Optional. The container and codec pairs the player advertises it can demux and decode directly.</param>
/// <param name="streamPath">Optional. The path of the track stream, relative to the API.</param>
/// <param name="segmentStreamPathTemplate">Optional. The path template of the segment route, relative to the API.</param>
/// <param name="includeLibraryId">Whether the library Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeArtistId">Whether the artist Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeAlbumId">Whether the album Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeTrackId">Whether the track Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeCapabilities">Whether the capabilities should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="GetPlaybackManifestQuery"/>.</returns>
public GetPlaybackManifestQuery Create(
string? libraryId = null,
string? artistId = null,
string? albumId = null,
string? trackId = null,
string? capabilities = null,
string? streamPath = null,
string? segmentStreamPathTemplate = null,
bool includeLibraryId = true,
bool includeArtistId = true,
bool includeAlbumId = true,
bool includeTrackId = true,
bool includeCapabilities = true)
{
return new GetPlaybackManifestQuery(
includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null,
includeArtistId ? (artistId ?? Guid.NewGuid().ToString()) : null,
includeAlbumId ? (albumId ?? Guid.NewGuid().ToString()) : null,
includeTrackId ? (trackId ?? Guid.NewGuid().ToString()) : null,
includeCapabilities ? (capabilities ?? "mp3/mp3,flac/flac") : null,
streamPath ?? "/api/v1/music/libraries/" + _faker.Random.AlphaNumeric(8) + "/tracks/" + _faker.Random.AlphaNumeric(8) + "/stream",
segmentStreamPathTemplate ?? "/api/v1/music/libraries/" + _faker.Random.AlphaNumeric(8) + "/tracks/" + _faker.Random.AlphaNumeric(8) + "/stream/segments/{deliveryId}/{segmentIndex}");
}
/// <summary>
/// Creates a list of <see cref="GetPlaybackManifestQuery"/> instances.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="GetPlaybackManifestQuery"/> instances.</returns>
public List<GetPlaybackManifestQuery> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,68 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrackSegment;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrackSegment;
/// <summary>
/// Fixture class for the <see cref="GetTrackSegmentQuery"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetTrackSegmentQueryFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid query to get a single segment of the normalized audio of a track.
/// </summary>
/// <param name="libraryId">Optional. The Id of the media library the track belongs to.</param>
/// <param name="artistId">Optional. The Id of the artist the album of the track belongs to.</param>
/// <param name="albumId">Optional. The Id of the album the track belongs to.</param>
/// <param name="trackId">Optional. The Id of the track whose normalized audio is streamed.</param>
/// <param name="deliveryId">Optional. The opaque handle of the normalized delivery the segment belongs to.</param>
/// <param name="segmentIndex">Optional. The zero based index of the segment of the normalized audio.</param>
/// <param name="includeLibraryId">Whether the library Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeArtistId">Whether the artist Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeAlbumId">Whether the album Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeTrackId">Whether the track Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeDeliveryId">Whether the delivery Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeSegmentIndex">Whether the segment index should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="GetTrackSegmentQuery"/>.</returns>
public GetTrackSegmentQuery Create(
string? libraryId = null,
string? artistId = null,
string? albumId = null,
string? trackId = null,
string? deliveryId = null,
string? segmentIndex = null,
bool includeLibraryId = true,
bool includeArtistId = true,
bool includeAlbumId = true,
bool includeTrackId = true,
bool includeDeliveryId = true,
bool includeSegmentIndex = true)
{
return new GetTrackSegmentQuery(
includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null,
includeArtistId ? (artistId ?? Guid.NewGuid().ToString()) : null,
includeAlbumId ? (albumId ?? Guid.NewGuid().ToString()) : null,
includeTrackId ? (trackId ?? Guid.NewGuid().ToString()) : null,
includeDeliveryId ? (deliveryId ?? Guid.NewGuid().ToString("N")) : null,
includeSegmentIndex ? (segmentIndex ?? _faker.Random.Int(0, 1000).ToString()) : null);
}
/// <summary>
/// Creates a list of <see cref="GetTrackSegmentQuery"/> instances.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="GetTrackSegmentQuery"/> instances.</returns>
public List<GetTrackSegmentQuery> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,119 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using Lumina.Domain.SharedKernel.Common.Enums.Playback;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
/// <summary>
/// Fixture class for the <see cref="PlaybackManifestResponse"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class PlaybackManifestResponseFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="PlaybackManifestResponse"/>.
/// </summary>
/// <param name="trackId">Optional. The Id of the track the manifest describes.</param>
/// <param name="durationInSeconds">Optional. The duration of the audio of the track, in seconds.</param>
/// <param name="sourceContainer">Optional. The container of the stored audio file of the track.</param>
/// <param name="sourceCodec">Optional. The codec of the stored audio of the track.</param>
/// <param name="sampleRate">Optional. The sample rate of the stored audio, in Hz.</param>
/// <param name="channels">Optional. The number of audio channels of the track.</param>
/// <param name="bitDepth">Optional. The bit depth of the stored audio of the track.</param>
/// <param name="replayGainTrackGain">Optional. The ReplayGain track gain of the track, in decibels.</param>
/// <param name="replayGainTrackPeak">Optional. The ReplayGain track peak of the track.</param>
/// <param name="replayGainAlbumGain">Optional. The ReplayGain album gain of the track, in decibels.</param>
/// <param name="replayGainAlbumPeak">Optional. The ReplayGain album peak of the track.</param>
/// <param name="isDirectPlay">Whether the stored audio is delivered as it is.</param>
/// <param name="deliveryContainer">Optional. The container of the delivered audio.</param>
/// <param name="deliveryCodec">Optional. The codec of the delivered audio.</param>
/// <param name="deliveryShape">Optional. The shape the delivered audio is addressed by.</param>
/// <param name="segmentDurationSeconds">Optional. The duration of each segment of the delivered audio, in seconds.</param>
/// <param name="isSeekable">Whether the delivered audio can be seeked by the player.</param>
/// <param name="streamPath">Optional. The relative path of the track stream.</param>
/// <param name="deliveryId">Optional. The opaque handle of the normalized delivery.</param>
/// <param name="segmentStreamPathTemplate">Optional. The relative path template of the segment route.</param>
/// <param name="includeBitDepth">Whether the bit depth should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeReplayGain">Whether the ReplayGain values should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeDeliveryContainer">Whether the delivery container should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeDeliveryCodec">Whether the delivery codec should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeDeliveryShape">Whether the delivery shape should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeSegmentDurationSeconds">Whether the segment duration should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeDeliveryId">Whether the delivery handle should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeSegmentStreamPathTemplate">Whether the segment path template should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="PlaybackManifestResponse"/>.</returns>
public PlaybackManifestResponse Create(
Guid? trackId = null,
int? durationInSeconds = null,
string? sourceContainer = null,
string? sourceCodec = null,
int? sampleRate = null,
int? channels = null,
int? bitDepth = null,
decimal? replayGainTrackGain = null,
decimal? replayGainTrackPeak = null,
decimal? replayGainAlbumGain = null,
decimal? replayGainAlbumPeak = null,
bool isDirectPlay = false,
string? deliveryContainer = null,
string? deliveryCodec = null,
PlaybackDeliveryShape? deliveryShape = null,
int? segmentDurationSeconds = null,
bool isSeekable = true,
string? streamPath = null,
string? deliveryId = null,
string? segmentStreamPathTemplate = null,
bool includeBitDepth = true,
bool includeReplayGain = true,
bool includeDeliveryContainer = true,
bool includeDeliveryCodec = true,
bool includeDeliveryShape = true,
bool includeSegmentDurationSeconds = true,
bool includeDeliveryId = true,
bool includeSegmentStreamPathTemplate = true)
{
Guid resolvedTrackId = trackId ?? _faker.Random.Guid();
string resolvedDeliveryId = deliveryId ?? Guid.NewGuid().ToString("N");
return new PlaybackManifestResponse(
resolvedTrackId,
durationInSeconds ?? _faker.Random.Int(1, 3600),
sourceContainer ?? _faker.PickRandom("FLAC", "MP3", "OGG", "MP4", "AAC", "WAV"),
sourceCodec ?? _faker.PickRandom("FLAC", "MP3", "AAC", "ALAC", "OPUS", "PCM"),
sampleRate ?? _faker.PickRandom(44100, 48000, 96000),
channels ?? _faker.PickRandom(1, 2, 6),
includeBitDepth ? (bitDepth ?? _faker.Random.Int(8, 32)) : null,
includeReplayGain ? (replayGainTrackGain ?? _faker.Random.Decimal(-20m, 0m)) : null,
includeReplayGain ? (replayGainTrackPeak ?? _faker.Random.Decimal(0m, 1.5m)) : null,
includeReplayGain ? (replayGainAlbumGain ?? _faker.Random.Decimal(-20m, 0m)) : null,
includeReplayGain ? (replayGainAlbumPeak ?? _faker.Random.Decimal(0m, 1.5m)) : null,
isDirectPlay,
includeDeliveryContainer ? (deliveryContainer ?? "MP3") : null,
includeDeliveryCodec ? (deliveryCodec ?? "MP3") : null,
includeDeliveryShape ? (deliveryShape ?? PlaybackDeliveryShape.TimeAddressedSegments) : null,
includeSegmentDurationSeconds ? (segmentDurationSeconds ?? 6) : null,
isSeekable,
streamPath ?? $"/libraries/{Guid.NewGuid():N}/artists/{Guid.NewGuid():N}/albums/{Guid.NewGuid():N}/tracks/{resolvedTrackId:N}/stream",
includeDeliveryId ? resolvedDeliveryId : null,
includeSegmentStreamPathTemplate
? (segmentStreamPathTemplate ?? $"/libraries/{Guid.NewGuid():N}/artists/{Guid.NewGuid():N}/albums/{Guid.NewGuid():N}/tracks/{resolvedTrackId:N}/stream/deliveries/{{deliveryId}}/segments/{{segmentIndex}}")
: null);
}
/// <summary>
/// Creates a list of <see cref="PlaybackManifestResponse"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="PlaybackManifestResponse"/> instances.</returns>
public List<PlaybackManifestResponse> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -1,6 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Infrastructure.Common.Models.DTO.Configuration;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
@@ -31,6 +32,7 @@ public class TranscodingSettingsDtoFixture
/// default temporary directory.
/// </param>
/// <param name="includeCacheDirectory">Whether to generate the optional cache directory, defaulting to <see langword="true"/>.</param>
/// <param name="includeFfmpegPath">Whether the ffmpeg path should be included, or forced to <see langword="null"/>, defaulting to <see langword="true"/>.</param>
/// <returns>A configured <see cref="TranscodingSettingsDto"/> instance.</returns>
public TranscodingSettingsDto Create(
string? ffmpegPath = null,
@@ -40,16 +42,19 @@ public class TranscodingSettingsDtoFixture
int? jobTimeoutSeconds = null,
int? evictionGraceSeconds = null,
string? cacheDirectory = null,
bool includeCacheDirectory = true)
bool includeCacheDirectory = true,
bool includeFfmpegPath = true)
{
int resolvedMaxConcurrentJobs = maxConcurrentJobs ?? _faker.Random.Int(1, 16);
return new TranscodingSettingsDto
{
FfmpegPath = ffmpegPath ?? _faker.System.FileName("exe"),
MaxConcurrentJobs = maxConcurrentJobs ?? _faker.Random.Int(1, 16),
MaxConcurrentJobsPerUser = maxConcurrentJobsPerUser ?? _faker.Random.Int(1, 8),
FfmpegPath = includeFfmpegPath ? (ffmpegPath ?? _faker.System.FileName("exe")) : null!,
MaxConcurrentJobs = resolvedMaxConcurrentJobs,
// A per-user limit above the global one is rejected by the validator, so the generated value never exceeds the global limit.
MaxConcurrentJobsPerUser = maxConcurrentJobsPerUser ?? _faker.Random.Int(1, Math.Max(1, resolvedMaxConcurrentJobs)),
MaxCacheBytes = maxCacheBytes ?? _faker.Random.Long(1_000_000_000, 8_589_934_592),
JobTimeoutSeconds = jobTimeoutSeconds ?? _faker.Random.Int(60, 3600),
EvictionGraceSeconds = evictionGraceSeconds ?? _faker.Random.Int(0, 600),
EvictionGraceSeconds = evictionGraceSeconds ?? _faker.Random.Int(1, 600),
CacheDirectory = includeCacheDirectory ? cacheDirectory ?? _faker.System.DirectoryPath() : null
};
}
@@ -0,0 +1,14 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Web.Fixtures.Common.Api;
/// <summary>
/// A streamed request that was sent to the <see cref="StubStreamingApiHttpClient"/> stub.
/// </summary>
/// <param name="Endpoint">The endpoint the stream was requested from.</param>
/// <param name="Headers">The request headers that were forwarded with the request.</param>
[ExcludeFromCodeCoverage]
public record StubStreamRequest(string Endpoint, IReadOnlyDictionary<string, string> Headers);
@@ -0,0 +1,90 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Api;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.Fixtures.Common.Api;
/// <summary>
/// Test double for the <see cref="IStreamingApiHttpClient"/> interface, allowing integration and security tests to stub the
/// streamed responses of the remote API without hosting a real backend.
/// </summary>
[ExcludeFromCodeCoverage]
public class StubStreamingApiHttpClient : IStreamingApiHttpClient
{
private readonly Dictionary<string, Func<ApiStreamResult>> _streamResponseFactories = [];
private readonly Dictionary<string, Func<Exception>> _streamExceptionFactories = [];
/// <summary>
/// Gets the streamed requests that were sent, with the headers that were forwarded with them.
/// </summary>
public List<StubStreamRequest> StreamRequests { get; } = [];
/// <summary>
/// Gets the list of endpoints the streams were requested from.
/// </summary>
public List<string> GetEndpointsCalled { get; } = [];
/// <summary>
/// Registers the streamed response returned when the specified endpoint is called.
/// </summary>
/// <param name="endpoint">The API endpoint for which to register the response.</param>
/// <param name="response">The streamed response to return.</param>
public void RegisterStreamResponse(string endpoint, ApiStreamResult response)
{
_streamResponseFactories[endpoint] = () => response;
}
/// <summary>
/// Registers the response factory invoked when the specified endpoint is called.
/// </summary>
/// <param name="endpoint">The API endpoint for which to register the response factory.</param>
/// <param name="responseFactory">The factory that produces the streamed response.</param>
public void RegisterStreamResponseFactory(string endpoint, Func<ApiStreamResult> responseFactory)
{
_streamResponseFactories[endpoint] = responseFactory;
}
/// <summary>
/// Registers the exception thrown when the specified endpoint is called.
/// </summary>
/// <param name="endpoint">The API endpoint for which to register the exception.</param>
/// <param name="exception">The exception to throw.</param>
public void RegisterStreamException(string endpoint, Exception exception)
{
_streamExceptionFactories[endpoint] = () => exception;
}
/// <summary>
/// Resets all registered responses and captured requests.
/// </summary>
public void Reset()
{
_streamResponseFactories.Clear();
_streamExceptionFactories.Clear();
StreamRequests.Clear();
GetEndpointsCalled.Clear();
}
/// <summary>
/// Sends a GET request to the specified <paramref name="endpoint"/> as an asynchronous operation and returns the response as a stream.
/// </summary>
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
/// <param name="requestHeaders">The range and conditional headers of the incoming request to forward.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The streamed response of the API request.</returns>
public Task<ApiStreamResult> GetStreamAsync(string endpoint, IReadOnlyDictionary<string, string> requestHeaders, CancellationToken cancellationToken = default)
{
GetEndpointsCalled.Add(endpoint);
StreamRequests.Add(new StubStreamRequest(endpoint, new Dictionary<string, string>(requestHeaders)));
if (_streamExceptionFactories.TryGetValue(endpoint, out Func<Exception>? exceptionFactory))
throw exceptionFactory();
if (_streamResponseFactories.TryGetValue(endpoint, out Func<ApiStreamResult>? responseFactory))
return Task.FromResult(responseFactory());
throw new InvalidOperationException($"No stream response is registered for the endpoint '{endpoint}'.");
}
}
@@ -0,0 +1,120 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
using Lumina.Presentation.Web.Common.Enums.AudioLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
/// <summary>
/// Fixture class for the <see cref="PlaybackManifestDto"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class PlaybackManifestDtoFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a new <see cref="PlaybackManifestDto"/> instance with randomized test data.
/// </summary>
/// <param name="trackId">Optional. The Id of the track the manifest describes.</param>
/// <param name="durationInSeconds">Optional. The duration of the audio of the track, in seconds.</param>
/// <param name="sourceContainer">Optional. The container of the stored audio file of the track.</param>
/// <param name="sourceCodec">Optional. The codec of the stored audio of the track.</param>
/// <param name="sampleRate">Optional. The sample rate of the stored audio, in Hz.</param>
/// <param name="channels">Optional. The number of audio channels of the track.</param>
/// <param name="bitDepth">Optional. The bit depth of the stored audio of the track.</param>
/// <param name="replayGainTrackGain">Optional. The ReplayGain track gain of the track, in decibels.</param>
/// <param name="replayGainTrackPeak">Optional. The ReplayGain track peak of the track.</param>
/// <param name="replayGainAlbumGain">Optional. The ReplayGain album gain of the track, in decibels.</param>
/// <param name="replayGainAlbumPeak">Optional. The ReplayGain album peak of the track.</param>
/// <param name="isDirectPlay">Whether the stored audio is delivered as it is.</param>
/// <param name="deliveryContainer">Optional. The container of the delivered audio.</param>
/// <param name="deliveryCodec">Optional. The codec of the delivered audio.</param>
/// <param name="deliveryShape">Optional. The shape the delivered audio is addressed by.</param>
/// <param name="segmentDurationSeconds">Optional. The duration of each segment of the delivered audio, in seconds.</param>
/// <param name="isSeekable">Whether the delivered audio can be seeked by the player.</param>
/// <param name="streamPath">Optional. The relative path of the track stream.</param>
/// <param name="deliveryId">Optional. The opaque handle of the normalized delivery.</param>
/// <param name="segmentStreamPathTemplate">Optional. The relative path template of the segment route.</param>
/// <param name="includeBitDepth">Whether the bit depth should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeReplayGain">Whether the ReplayGain values should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeDeliveryContainer">Whether the delivery container should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeDeliveryCodec">Whether the delivery codec should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeDeliveryShape">Whether the delivery shape should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeSegmentDurationSeconds">Whether the segment duration should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeDeliveryId">Whether the delivery handle should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeSegmentStreamPathTemplate">Whether the segment path template should be included, or forced to <see langword="null"/>.</param>
/// <returns>A configured <see cref="PlaybackManifestDto"/> instance.</returns>
public PlaybackManifestDto Create(
Guid? trackId = null,
int? durationInSeconds = null,
string? sourceContainer = null,
string? sourceCodec = null,
int? sampleRate = null,
int? channels = null,
int? bitDepth = null,
decimal? replayGainTrackGain = null,
decimal? replayGainTrackPeak = null,
decimal? replayGainAlbumGain = null,
decimal? replayGainAlbumPeak = null,
bool isDirectPlay = false,
string? deliveryContainer = null,
string? deliveryCodec = null,
PlaybackDeliveryShape? deliveryShape = null,
int? segmentDurationSeconds = null,
bool isSeekable = true,
string? streamPath = null,
string? deliveryId = null,
string? segmentStreamPathTemplate = null,
bool includeBitDepth = true,
bool includeReplayGain = true,
bool includeDeliveryContainer = true,
bool includeDeliveryCodec = true,
bool includeDeliveryShape = true,
bool includeSegmentDurationSeconds = true,
bool includeDeliveryId = true,
bool includeSegmentStreamPathTemplate = true)
{
Guid resolvedTrackId = trackId ?? _faker.Random.Guid();
return new PlaybackManifestDto
{
TrackId = resolvedTrackId,
DurationInSeconds = durationInSeconds ?? _faker.Random.Int(1, 3600),
SourceContainer = sourceContainer ?? _faker.PickRandom("FLAC", "MP3", "OGG", "MP4", "AAC", "WAV"),
SourceCodec = sourceCodec ?? _faker.PickRandom("FLAC", "MP3", "AAC", "ALAC", "OPUS", "PCM"),
SampleRate = sampleRate ?? _faker.PickRandom(44100, 48000, 96000),
Channels = channels ?? _faker.PickRandom(1, 2, 6),
BitDepth = includeBitDepth ? (bitDepth ?? _faker.Random.Int(8, 32)) : null,
ReplayGainTrackGain = includeReplayGain ? (replayGainTrackGain ?? _faker.Random.Decimal(-20m, 0m)) : null,
ReplayGainTrackPeak = includeReplayGain ? (replayGainTrackPeak ?? _faker.Random.Decimal(0m, 1.5m)) : null,
ReplayGainAlbumGain = includeReplayGain ? (replayGainAlbumGain ?? _faker.Random.Decimal(-20m, 0m)) : null,
ReplayGainAlbumPeak = includeReplayGain ? (replayGainAlbumPeak ?? _faker.Random.Decimal(0m, 1.5m)) : null,
IsDirectPlay = isDirectPlay,
DeliveryContainer = includeDeliveryContainer ? (deliveryContainer ?? "MP3") : null,
DeliveryCodec = includeDeliveryCodec ? (deliveryCodec ?? "MP3") : null,
DeliveryShape = includeDeliveryShape ? (deliveryShape ?? PlaybackDeliveryShape.TimeAddressedSegments) : null,
SegmentDurationSeconds = includeSegmentDurationSeconds ? (segmentDurationSeconds ?? 6) : null,
IsSeekable = isSeekable,
StreamPath = streamPath ?? $"/libraries/{Guid.NewGuid():N}/artists/{Guid.NewGuid():N}/albums/{Guid.NewGuid():N}/tracks/{resolvedTrackId:N}/stream",
DeliveryId = includeDeliveryId ? (deliveryId ?? Guid.NewGuid().ToString("N")) : null,
SegmentStreamPathTemplate = includeSegmentStreamPathTemplate
? (segmentStreamPathTemplate ?? $"/libraries/{Guid.NewGuid():N}/artists/{Guid.NewGuid():N}/albums/{Guid.NewGuid():N}/tracks/{resolvedTrackId:N}/stream/deliveries/{{deliveryId}}/segments/{{segmentIndex}}")
: null
};
}
/// <summary>
/// Creates multiple <see cref="PlaybackManifestDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="PlaybackManifestDto"/> instances.</returns>
public List<PlaybackManifestDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,52 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
/// <summary>
/// Fixture class for the <see cref="GetPlaybackManifestRequest"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetPlaybackManifestRequestFixture
{
/// <summary>
/// Creates a new <see cref="GetPlaybackManifestRequest"/> instance.
/// </summary>
/// <param name="artistId">Optional unique identifier of the artist the album belongs to.</param>
/// <param name="albumId">Optional unique identifier of the album the track belongs to.</param>
/// <param name="trackId">Optional unique identifier of the track whose manifest is requested.</param>
/// <param name="libraryId">Optional unique identifier of the media library the track belongs to.</param>
/// <param name="capabilities">Optional capabilities the player advertises it can play directly.</param>
/// <param name="includeCapabilities">Whether the capabilities should be included, or forced to <see langword="null"/>.</param>
/// <returns>A configured <see cref="GetPlaybackManifestRequest"/> instance.</returns>
public GetPlaybackManifestRequest Create(
string? artistId = null,
string? albumId = null,
string? trackId = null,
Guid? libraryId = null,
string? capabilities = null,
bool includeCapabilities = true)
{
return new GetPlaybackManifestRequest(
artistId ?? Guid.NewGuid().ToString(),
albumId ?? Guid.NewGuid().ToString(),
trackId ?? Guid.NewGuid().ToString(),
libraryId ?? Guid.NewGuid(),
includeCapabilities ? (capabilities ?? "mp3/mp3") : null);
}
/// <summary>
/// Creates a list of <see cref="GetPlaybackManifestRequest"/> instances.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="GetPlaybackManifestRequest"/> instances.</returns>
public List<GetPlaybackManifestRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,53 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
/// <summary>
/// Fixture class for the <see cref="StreamMusicTrackRequest"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class StreamMusicTrackRequestFixture
{
/// <summary>
/// Creates a new <see cref="StreamMusicTrackRequest"/> instance.
/// </summary>
/// <param name="artistId">Optional unique identifier of the artist the album belongs to.</param>
/// <param name="albumId">Optional unique identifier of the album the track belongs to.</param>
/// <param name="trackId">Optional unique identifier of the track to stream.</param>
/// <param name="libraryId">Optional unique identifier of the media library the track belongs to.</param>
/// <param name="includeArtistId">Whether the artist Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeAlbumId">Whether the album Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeTrackId">Whether the track Id should be included, or forced to <see langword="null"/>.</param>
/// <returns>A configured <see cref="StreamMusicTrackRequest"/> instance.</returns>
public StreamMusicTrackRequest Create(
string? artistId = null,
string? albumId = null,
string? trackId = null,
Guid? libraryId = null,
bool includeArtistId = true,
bool includeAlbumId = true,
bool includeTrackId = true)
{
return new StreamMusicTrackRequest(
includeArtistId ? (artistId ?? Guid.NewGuid().ToString()) : null!,
includeAlbumId ? (albumId ?? Guid.NewGuid().ToString()) : null!,
includeTrackId ? (trackId ?? Guid.NewGuid().ToString()) : null!,
libraryId ?? Guid.NewGuid());
}
/// <summary>
/// Creates a list of <see cref="StreamMusicTrackRequest"/> instances.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="StreamMusicTrackRequest"/> instances.</returns>
public List<StreamMusicTrackRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,55 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
/// <summary>
/// Fixture class for the <see cref="StreamMusicTrackSegmentRequest"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class StreamMusicTrackSegmentRequestFixture
{
/// <summary>
/// Creates a new <see cref="StreamMusicTrackSegmentRequest"/> instance.
/// </summary>
/// <param name="artistId">Optional unique identifier of the artist the album belongs to.</param>
/// <param name="albumId">Optional unique identifier of the album the track belongs to.</param>
/// <param name="trackId">Optional unique identifier of the track to stream.</param>
/// <param name="deliveryId">Optional opaque handle of the normalized delivery.</param>
/// <param name="segmentIndex">Optional zero based index of the segment.</param>
/// <param name="libraryId">Optional unique identifier of the media library the track belongs to.</param>
/// <param name="includeDeliveryId">Whether the delivery handle should be included, or forced to <see langword="null"/>.</param>
/// <returns>A configured <see cref="StreamMusicTrackSegmentRequest"/> instance.</returns>
public StreamMusicTrackSegmentRequest Create(
string? artistId = null,
string? albumId = null,
string? trackId = null,
string? deliveryId = null,
int? segmentIndex = null,
Guid? libraryId = null,
bool includeDeliveryId = true)
{
return new StreamMusicTrackSegmentRequest(
artistId ?? Guid.NewGuid().ToString(),
albumId ?? Guid.NewGuid().ToString(),
trackId ?? Guid.NewGuid().ToString(),
includeDeliveryId ? (deliveryId ?? Guid.NewGuid().ToString("N")) : null!,
segmentIndex ?? Random.Shared.Next(0, 100),
libraryId ?? Guid.NewGuid());
}
/// <summary>
/// Creates a list of <see cref="StreamMusicTrackSegmentRequest"/> instances.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="StreamMusicTrackSegmentRequest"/> instances.</returns>
public List<StreamMusicTrackSegmentRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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>
@@ -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();
}
}
@@ -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>();
});
@@ -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;
}
}
@@ -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))];
}
}
@@ -0,0 +1,316 @@
#region ========================================================================= USING =====================================================================================
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.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
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.SecurityTests.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.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetTrackSegment;
/// <summary>
/// Contains security tests for the <see cref="GetTrackSegmentEndpoint"/> class.
/// </summary>
/// <remarks>
/// The concurrency rate limiter of the segment route is not exercised, because it requires four concurrent long lived streams, which needs a real
/// normalization pipeline and ffmpeg, neither of which is available in the test environment.
/// </remarks>
[ExcludeFromCodeCoverage]
public class GetTrackSegmentEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private const int DEFAULT_SEGMENT_INDEX = 0;
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly string _contentRootPath = Path.Combine(Path.GetTempPath(), $"lumina-track-segment-security-tests-{Guid.NewGuid():N}");
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();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly List<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="GetTrackSegmentEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetTrackSegmentEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
// A unique X-Forwarded-For isolates rate limiting state per test.
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
Directory.CreateDirectory(_contentRootPath);
}
[Fact]
public async Task GetTrackSegment_WhenCalledWithoutCredentials_ShouldReturnUnauthorizedResult()
{
// Act
HttpResponseMessage response = await _client.GetAsync(BuildSegmentPath(Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid().ToString("N"), 0));
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal("Unauthorized", problemDetails!["title"].GetString());
}
[Theory]
[InlineData("libraryId", "'; DROP TABLE Tracks; --")] // destructive injection in the library Id
[InlineData("libraryId", "' OR '1'='1")] // boolean based injection in the library Id
[InlineData("artistId", "'; DROP TABLE Tracks; --")] // destructive injection in the artist Id
[InlineData("artistId", "'; EXEC xp_cmdshell('dir'); --")] // command execution attempt in the artist Id
[InlineData("albumId", "' OR '1'='1")] // boolean based injection in the album Id
[InlineData("albumId", "'; DROP TABLE Tracks; --")] // destructive injection in the album Id
[InlineData("trackId", "' OR '1'='1")] // boolean based injection in the track Id
[InlineData("trackId", "'; EXEC xp_cmdshell('dir'); --")] // command execution attempt in the track Id
[InlineData("deliveryId", "'; DROP TABLE Tracks; --")] // destructive injection in the delivery handle
[InlineData("deliveryId", "' OR '1'='1")] // boolean based injection in the delivery handle
[InlineData("segmentIndex", "'; DROP TABLE Tracks; --")] // destructive injection in the segment index
[InlineData("segmentIndex", "' OR '1'='1")] // boolean based injection in the segment index
[InlineData("libraryId", "../../etc/passwd")] // path traversal in the library Id
[InlineData("artistId", "../../etc/passwd")] // path traversal in the artist Id
[InlineData("albumId", "../../etc/passwd")] // path traversal in the album Id
[InlineData("trackId", "../../etc/passwd")] // path traversal in the track Id
[InlineData("deliveryId", "../../etc/passwd")] // path traversal in the delivery handle
[InlineData("segmentIndex", "../../etc/passwd")] // path traversal in the segment index
public async Task GetTrackSegment_WithAnInjectionPayloadInARouteValue_ShouldNotFailOrLeakData(string routeValue, string payload)
{
// Arrange
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
string path = BuildSegmentPathWithPayload(routeValue, payload);
// Act
HttpResponseMessage response = await _client.GetAsync(path);
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode);
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(payload, content, StringComparison.Ordinal);
Assert.DoesNotContain("/etc/passwd", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("C:\\", content, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task GetTrackSegment_WhenDeliveryIdIsWellFormedButUnknown_ShouldReturnGenericNotFound()
{
// Arrange
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
// A library owned by the authenticated user keeps the ownership check passing, so the unknown handle is what rejects the request.
Guid libraryId = await SeedLibraryAsync(userId);
string unknownDeliveryId = Guid.NewGuid().ToString("N");
// Act
HttpResponseMessage response = await _client.GetAsync(BuildSegmentPath(libraryId, Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), unknownDeliveryId, 0));
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
Microsoft.AspNetCore.Mvc.ProblemDetails? problemDetails = JsonSerializer.Deserialize<Microsoft.AspNetCore.Mvc.ProblemDetails>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal("General.NotFound", problemDetails!.Title);
Assert.Equal("PlaybackDeliveryNotFound", problemDetails.Detail);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task GetTrackSegment_WhenLibraryBelongsToAnotherUser_ShouldReturnForbiddenWithoutLeakingTheTrackPath()
{
// Arrange
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
Guid otherUserId = await SeedOtherUserAsync();
string secretTrackPath = Path.Combine(_contentRootPath, $"secret-{Guid.NewGuid():N}.flac");
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(otherUserId, secretTrackPath);
// Act
HttpResponseMessage response = await _client.GetAsync(BuildSegmentPath(libraryId, artistId, albumId, trackId, Guid.NewGuid().ToString("N"), 0));
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Assert.DoesNotContain("secret-", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(secretTrackPath, content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal("General.Unauthorized", problemDetails!["title"].GetString());
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
}
[Fact]
public async Task GetTrackSegment_WhenManifestHandleIsUsedForAnotherTrack_ShouldReturnNotFound()
{
// Arrange
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
string trackPath = Path.Combine(_contentRootPath, $"delivered-{Guid.NewGuid():N}.ogg");
await File.WriteAllBytesAsync(trackPath, [1, 2, 3, 4, 5, 6, 7, 8]);
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, trackPath);
string deliveryId = await GetDeliveryIdAsync(libraryId, artistId, albumId, trackId);
Guid otherTrackId = Guid.NewGuid();
// Act
HttpResponseMessage response = await _client.GetAsync(BuildSegmentPath(libraryId, artistId, albumId, otherTrackId, deliveryId, 0));
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
Microsoft.AspNetCore.Mvc.ProblemDetails? problemDetails = JsonSerializer.Deserialize<Microsoft.AspNetCore.Mvc.ProblemDetails>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal("General.NotFound", problemDetails!.Title);
Assert.Equal("PlaybackDeliveryNotFound", problemDetails.Detail);
Assert.DoesNotContain(trackPath, content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id.
/// </summary>
/// <returns>The Id of the seeded other user.</returns>
private async Task<Guid> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
string username = $"otheruser_{Guid.NewGuid()}";
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
await dbContext.SaveChangesAsync();
_seededUsernames.Add(username);
return userId;
}
/// <summary>
/// Seeds a 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 Library", libraryType: LibraryType.Music, contentLocations: []));
await dbContext.SaveChangesAsync();
return libraryId;
}
/// <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();
return (libraryId, artistId, albumId, trackId);
}
/// <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>
/// Builds the route of a single segment of the normalized audio of a track, with a malicious payload in one of its route values.
/// </summary>
/// <param name="routeValue">The name of the route value that carries the payload.</param>
/// <param name="payload">The malicious payload.</param>
/// <returns>The route of the requested segment, with the payload URL-escaped.</returns>
private static string BuildSegmentPathWithPayload(string routeValue, string payload)
{
string libraryId = routeValue == "libraryId" ? Uri.EscapeDataString(payload) : Guid.NewGuid().ToString();
string artistId = routeValue == "artistId" ? Uri.EscapeDataString(payload) : Guid.NewGuid().ToString();
string albumId = routeValue == "albumId" ? Uri.EscapeDataString(payload) : Guid.NewGuid().ToString();
string trackId = routeValue == "trackId" ? Uri.EscapeDataString(payload) : Guid.NewGuid().ToString();
string deliveryId = routeValue == "deliveryId" ? Uri.EscapeDataString(payload) : Guid.NewGuid().ToString("N");
string segmentIndex = routeValue == "segmentIndex" ? Uri.EscapeDataString(payload) : DEFAULT_SEGMENT_INDEX.ToString();
return $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream/deliveries/{deliveryId}/segments/{segmentIndex}";
}
/// <summary>
/// Disposes the API factory resources, the seeded users and the temporary files of the test.
/// </summary>
public void Dispose()
{
_client.Dispose();
if (Directory.Exists(_contentRootPath))
Directory.Delete(_contentRootPath, recursive: true);
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -1,15 +1,11 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Fixtures.Common.Api;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Presentation.Web.SecurityTests.Common.Setup;
@@ -27,6 +23,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>
@@ -42,7 +43,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,
@@ -53,11 +54,17 @@ 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);
// 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);
});
}
}
@@ -0,0 +1,201 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Api;
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.SecurityTests.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.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.StreamMusicTrackSegment;
/// <summary>
/// Contains security tests for the <see cref="StreamMusicTrackSegmentEndpoint"/> class.
/// </summary>
/// <remarks>
/// The concurrency rate limiter of the segment route is not exercised, because it requires four concurrent long lived streams, which needs a real
/// normalization pipeline and ffmpeg, neither of which is available in the test environment.
/// </remarks>
[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_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);
}
[Theory]
[InlineData("'; DROP TABLE Tracks; --")] // destructive injection in the delivery handle
[InlineData("' OR '1'='1")] // boolean based injection in the delivery handle
[InlineData("../../etc/passwd")] // path traversal in the delivery handle
public async Task StreamMusicTrackSegment_WithAnInjectionPayloadInDeliveryId_ShouldRejectTheRequestWithoutCallingTheApi(string payload)
{
// 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(),
Uri.EscapeDataString(payload),
0));
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
Assert.Equal(string.Empty, content);
Assert.DoesNotContain(payload, content, StringComparison.Ordinal);
Assert.Empty(_apiFactory.StreamingApiClientStub.GetEndpointsCalled);
}
[Theory]
[InlineData("artistId")] // injection in the artist Id
[InlineData("albumId")] // injection in the album Id
[InlineData("trackId")] // injection in the track Id
public async Task StreamMusicTrackSegment_WithAnInjectionPayloadInATrackRouteId_ShouldNormalizeTheIdWithoutLeakingData(string routeValue)
{
// Arrange
_apiFactory.ApiClientStub.Reset();
_apiFactory.StreamingApiClientStub.Reset();
const string PAYLOAD = "'; DROP TABLE Tracks; --";
Guid libraryId = Guid.NewGuid();
string validArtistId = Guid.NewGuid().ToString();
string validAlbumId = Guid.NewGuid().ToString();
string validTrackId = Guid.NewGuid().ToString();
string deliveryId = Guid.NewGuid().ToString("N");
string artistId = routeValue == "artistId" ? Uri.EscapeDataString(PAYLOAD) : validArtistId;
string albumId = routeValue == "albumId" ? Uri.EscapeDataString(PAYLOAD) : validAlbumId;
string trackId = routeValue == "trackId" ? Uri.EscapeDataString(PAYLOAD) : validTrackId;
string expectedEndpoint = ApiRoutes.Music.STREAM_TRACK_SEGMENT
.Replace("{libraryId}", libraryId.ToString())
.Replace("{artistId}", routeValue == "artistId" ? Guid.Empty.ToString() : validArtistId)
.Replace("{albumId}", routeValue == "albumId" ? Guid.Empty.ToString() : validAlbumId)
.Replace("{trackId}", routeValue == "trackId" ? Guid.Empty.ToString() : validTrackId)
.Replace("{deliveryId}", deliveryId)
.Replace("{segmentIndex}", "0");
byte[] contentBytes = CreateBytes(128);
_apiFactory.StreamingApiClientStub.RegisterStreamResponse(expectedEndpoint, await CreateStreamResultAsync(contentBytes));
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
// Act
HttpResponseMessage response = await webClient.Client.GetAsync(
$"/en-us/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-stream-track-segment/{deliveryId}/0?libraryId={libraryId}");
byte[] responseBytes = await response.Content.ReadAsByteArrayAsync();
// Assert
Assert.Equal(HttpStatusCode.PartialContent, response.StatusCode);
Assert.Equal(contentBytes, responseBytes);
Assert.DoesNotContain("SQL", System.Text.Encoding.UTF8.GetString(responseBytes), StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", System.Text.Encoding.UTF8.GetString(responseBytes), StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("at Lumina", System.Text.Encoding.UTF8.GetString(responseBytes), StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(PAYLOAD, System.Text.Encoding.UTF8.GetString(responseBytes), StringComparison.Ordinal);
Assert.Single(_apiFactory.StreamingApiClientStub.GetEndpointsCalled);
Assert.Equal(expectedEndpoint, _apiFactory.StreamingApiClientStub.GetEndpointsCalled[0]);
}
[Fact]
public async Task StreamMusicTrackSegment_WhenTheApiDeclaresAPublicCache_ShouldNeverExposeAPublicCacheControl()
{
// 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 = 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}", "0");
_apiFactory.StreamingApiClientStub.RegisterStreamResponse(expectedEndpoint, await CreateStreamResultAsync(CreateBytes(64)));
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
// Act
HttpResponseMessage response = await webClient.Client.GetAsync(BuildBrowserPath(libraryId, artistId, albumId, trackId, deliveryId, 0));
// Assert
Assert.Equal(HttpStatusCode.PartialContent, response.StatusCode);
string cacheControl = response.Headers.CacheControl?.ToString() ?? string.Empty;
Assert.DoesNotContain("public", cacheControl, StringComparison.OrdinalIgnoreCase);
Assert.Contains("private", cacheControl);
Assert.Contains("Cookie", response.Headers.Vary);
}
/// <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>
/// Creates a streamed API response with a partial content status and a body.
/// </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(120) };
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))];
}
}
@@ -0,0 +1,70 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
/// <summary>
/// Contains unit tests for the <see cref="PlaybackDeliveryId"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class PlaybackDeliveryIdTests
{
[Fact]
public void CHARACTER_COUNT_WhenAccessed_ShouldBeThirtyTwo()
{
// Act
int characterCount = PlaybackDeliveryId.CHARACTER_COUNT;
// Assert
Assert.Equal(32, characterCount);
}
[Fact]
public void IsValid_WhenValueIsTheNFormatOfAGuid_ShouldReturnTrue()
{
// Arrange
string value = Guid.NewGuid().ToString("N");
// Act
bool isValid = PlaybackDeliveryId.IsValid(value);
// Assert
Assert.True(isValid);
}
[Fact]
public void IsValid_WhenValueIsTheLowestPossibleHandle_ShouldReturnTrue()
{
// Arrange
string value = Guid.Empty.ToString("N");
// Act
bool isValid = PlaybackDeliveryId.IsValid(value);
// Assert
Assert.True(isValid);
}
[Theory]
[InlineData(null)] // an absent handle cannot address a delivery
[InlineData("")] // an empty handle has the wrong length
[InlineData(" ")] // a whitespace handle has the wrong length
[InlineData(" ")] // a handle made only of whitespace has the right length but is not hexadecimal
[InlineData("0123456789abcdef0123456789abcde")] // 31 characters, one short of a handle
[InlineData("0123456789abcdef0123456789abcdef0")] // 33 characters, one over a handle
[InlineData("0123456789ABCDEF0123456789ABCDEF")] // uppercase hexadecimal is not the canonical lowercase form
[InlineData("01234567-89ab-cdef-0123-456789abcdef")] // the D format of a Guid carries dashes
[InlineData("0123456789abcdef0123456789abcdeg")] // the last character is not a hexadecimal digit
[InlineData("zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz")] // no character is a hexadecimal digit
public void IsValid_WhenValueIsNotACanonicalHandle_ShouldReturnFalse(string? value)
{
// Act
bool isValid = PlaybackDeliveryId.IsValid(value);
// Assert
Assert.False(isValid);
}
}
@@ -0,0 +1,650 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
using Lumina.Application.Common.DataAccess.Repositories.Users;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetPlaybackManifest;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetPlaybackManifest;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.SharedKernel.Common.Enums.Playback;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetPlaybackManifest;
/// <summary>
/// Contains unit tests for the <see cref="GetPlaybackManifestQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetPlaybackManifestQueryHandlerTests : IDisposable
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ITrackRepository _mockTrackRepository;
private readonly IUserSettingsRepository _mockUserSettingsRepository;
private readonly ILibraryRepository _mockLibraryRepository;
private readonly IPlaybackFormatService _mockPlaybackFormatService;
private readonly IPlaybackDeliveryHandleService _mockPlaybackDeliveryHandleService;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IPathService _mockPathService;
private readonly IValidator<GetPlaybackManifestQuery> _mockValidator;
private readonly GetPlaybackManifestQueryHandler _sut;
private readonly Guid _userId;
private readonly string _issuedDeliveryId;
private readonly string _sandboxRoot;
private readonly string _libraryRoot;
private readonly string _sourcePath;
private PlaybackDeliveryHandleDto? _issuedDelivery;
private readonly GetPlaybackManifestQueryFixture _getPlaybackManifestQueryFixture = new();
private readonly TrackPlaybackManifestDtoFixture _trackPlaybackManifestDtoFixture = new();
private readonly PlaybackDeliveryDecisionDtoFixture _playbackDeliveryDecisionDtoFixture = new();
private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetPlaybackManifestQueryHandlerTests"/> class.
/// </summary>
public GetPlaybackManifestQueryHandlerTests()
{
_mockTrackRepository = Substitute.For<ITrackRepository>();
_mockUserSettingsRepository = Substitute.For<IUserSettingsRepository>();
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.TrackRepository.Returns(_mockTrackRepository);
_mockUnitOfWork.UserSettingsRepository.Returns(_mockUserSettingsRepository);
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
_mockPlaybackFormatService = Substitute.For<IPlaybackFormatService>();
_mockPlaybackDeliveryHandleService = Substitute.For<IPlaybackDeliveryHandleService>();
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockPathService = Substitute.For<IPathService>();
_mockValidator = Substitute.For<IValidator<GetPlaybackManifestQuery>>();
_userId = Guid.NewGuid();
_issuedDeliveryId = Guid.NewGuid().ToString("N");
_sandboxRoot = Path.Combine(Path.GetTempPath(), "lumina-playback-manifest-tests-" + Guid.NewGuid().ToString("N"));
_libraryRoot = Path.Combine(_sandboxRoot, "library");
_sourcePath = Path.Combine(_libraryRoot, "track.flac");
Directory.CreateDirectory(_libraryRoot);
// Default stubs: the user is authenticated, the library ownership policy allows access, the query validates and every path is inside its content location.
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
_mockValidator.Validate(Arg.Any<GetPlaybackManifestQuery>()).Returns([]);
_mockPathService.IsPathWithin(Arg.Any<string>(), Arg.Any<string>()).Returns(true);
_sut = new GetPlaybackManifestQueryHandler(
_mockUnitOfWork,
_mockPlaybackFormatService,
_mockPlaybackDeliveryHandleService,
_mockAuthorizationService,
_mockCurrentUserService,
_mockPathService,
_mockValidator);
}
[Fact]
public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutReadingAnything()
{
// Arrange
GetPlaybackManifestQuery query = _getPlaybackManifestQueryFixture.Create();
_mockValidator.Validate(Arg.Any<GetPlaybackManifestQuery>()).Returns([Errors.Library.LibraryIdCannotBeEmpty]);
// Act
Result<PlaybackManifestResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockTrackRepository.DidNotReceive().GetPlaybackManifestInfoAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
GetPlaybackManifestQuery query = _getPlaybackManifestQueryFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<PlaybackManifestResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenLibraryOwnershipIsDenied_ShouldReturnNotAuthorizedError()
{
// Arrange
GetPlaybackManifestQuery query = _getPlaybackManifestQueryFixture.Create();
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<PlaybackManifestResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockTrackRepository.DidNotReceive().GetPlaybackManifestInfoAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenTheTrackLookupFails_ShouldReturnItsError()
{
// Arrange
GetPlaybackManifestQuery query = _getPlaybackManifestQueryFixture.Create();
Guid libraryId = Guid.Parse(query.LibraryId!);
Guid albumId = Guid.Parse(query.AlbumId!);
Guid artistId = Guid.Parse(query.ArtistId!);
Guid trackId = Guid.Parse(query.TrackId!);
_mockTrackRepository.GetPlaybackManifestInfoAsync(libraryId, albumId, artistId, trackId, Arg.Any<CancellationToken>())
.Returns(Errors.Music.TrackFileNotFound);
// Act
Result<PlaybackManifestResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.TrackFileNotFound, result.FirstError);
_mockPlaybackFormatService.DidNotReceive().DecideDelivery(Arg.Any<PlaybackSourceFormatDto>(), Arg.Any<IReadOnlyList<PlaybackCapabilityDto>>());
}
[Fact]
public async Task HandleAsync_WhenTheTrackIsNotFound_ShouldReturnTrackNotFoundError()
{
// Arrange
GetPlaybackManifestQuery query = _getPlaybackManifestQueryFixture.Create();
Guid libraryId = Guid.Parse(query.LibraryId!);
Guid albumId = Guid.Parse(query.AlbumId!);
Guid artistId = Guid.Parse(query.ArtistId!);
Guid trackId = Guid.Parse(query.TrackId!);
_mockTrackRepository.GetPlaybackManifestInfoAsync(libraryId, albumId, artistId, trackId, Arg.Any<CancellationToken>())
.Returns(Result.From<TrackPlaybackManifestDto?>(null));
// Act
Result<PlaybackManifestResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.TrackNotFound, result.FirstError);
_mockPlaybackFormatService.DidNotReceive().DecideDelivery(Arg.Any<PlaybackSourceFormatDto>(), Arg.Any<IReadOnlyList<PlaybackCapabilityDto>>());
}
[Fact]
public async Task HandleAsync_WhenTheDeliveryDecisionFails_ShouldReturnItsError()
{
// Arrange
GetPlaybackManifestQuery query = _getPlaybackManifestQueryFixture.Create();
TrackPlaybackManifestDto track = _trackPlaybackManifestDtoFixture.Create(
path: _sourcePath, container: "AIFF", audioCodec: "PCM");
StubTrackLookup(query, track);
_mockPlaybackFormatService.DecideDelivery(Arg.Any<PlaybackSourceFormatDto>(), Arg.Any<IReadOnlyList<PlaybackCapabilityDto>>())
.Returns(Errors.Playback.NoSupportedPlaybackFormat);
// Act
Result<PlaybackManifestResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Playback.NoSupportedPlaybackFormat, result.FirstError);
await _mockUserSettingsRepository.DidNotReceive().GetByUserIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenTheStoredAudioIsPlayedDirectly_ShouldReturnTheStoredFieldsWithoutIssuingADelivery()
{
// Arrange
GetPlaybackManifestQuery query = _getPlaybackManifestQueryFixture.Create();
TrackPlaybackManifestDto track = _trackPlaybackManifestDtoFixture.Create(
path: _sourcePath,
container: "FLAC",
audioCodec: "FLAC",
durationInSeconds: 245,
sampleRate: 48000,
channels: 2,
bitDepth: 24,
replayGainTrackGain: -6.5m,
replayGainTrackPeak: 0.98m,
replayGainAlbumGain: -7.1m,
replayGainAlbumPeak: 0.97m);
PlaybackDeliveryDecisionDto decision = _playbackDeliveryDecisionDtoFixture.Create(
mode: PlaybackDeliveryMode.DirectPlay,
container: "FLAC",
codec: "FLAC",
shape: PlaybackDeliveryShape.ByteRangeSeekable,
segmentDurationSeconds: 0);
StubTrackLookup(query, track);
_mockPlaybackFormatService.DecideDelivery(Arg.Any<PlaybackSourceFormatDto>(), Arg.Any<IReadOnlyList<PlaybackCapabilityDto>>())
.Returns(Result.From(decision));
// Act
Result<PlaybackManifestResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Guid.Parse(query.TrackId!), result.Value.TrackId);
Assert.Equal(245, result.Value.DurationInSeconds);
Assert.Equal("FLAC", result.Value.SourceContainer);
Assert.Equal("FLAC", result.Value.SourceCodec);
Assert.Equal(48000, result.Value.SampleRate);
Assert.Equal(2, result.Value.Channels);
Assert.Equal(24, result.Value.BitDepth);
Assert.Equal(-6.5m, result.Value.ReplayGainTrackGain);
Assert.Equal(0.98m, result.Value.ReplayGainTrackPeak);
Assert.Equal(-7.1m, result.Value.ReplayGainAlbumGain);
Assert.Equal(0.97m, result.Value.ReplayGainAlbumPeak);
Assert.True(result.Value.IsDirectPlay);
Assert.Null(result.Value.DeliveryContainer);
Assert.Null(result.Value.DeliveryCodec);
Assert.Null(result.Value.DeliveryShape);
Assert.Null(result.Value.SegmentDurationSeconds);
Assert.True(result.Value.IsSeekable);
Assert.Equal(query.StreamPath, result.Value.StreamPath);
Assert.Null(result.Value.DeliveryId);
Assert.Null(result.Value.SegmentStreamPathTemplate);
_mockPlaybackDeliveryHandleService.DidNotReceive().IssueDeliveryId(Arg.Any<PlaybackDeliveryHandleDto>());
await _mockUserSettingsRepository.DidNotReceive().GetByUserIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenTheUserHasNoSettings_ShouldCapTheNormalizedDeliveryAtAutoQuality()
{
// Arrange
GetPlaybackManifestQuery query = _getPlaybackManifestQueryFixture.Create();
TrackPlaybackManifestDto track = _trackPlaybackManifestDtoFixture.Create(path: _sourcePath);
StubNormalizedDelivery(query, track, settings: null);
CaptureIssuedDelivery();
// Act
Result<PlaybackManifestResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.NotNull(_issuedDelivery);
Assert.Equal(PlaybackStreamingQuality.Auto, _issuedDelivery.Request.Quality);
await _mockUserSettingsRepository.Received(1).GetByUserIdAsync(_userId, Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenTheUserSettingsCannotBeRead_ShouldReturnTheirError()
{
// Arrange
GetPlaybackManifestQuery query = _getPlaybackManifestQueryFixture.Create();
TrackPlaybackManifestDto track = _trackPlaybackManifestDtoFixture.Create(path: _sourcePath);
StubTrackLookup(query, track);
StubNormalizedDecision();
_mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any<CancellationToken>())
.Returns(Errors.UserSettings.UserSettingsNotFound);
// Act
Result<PlaybackManifestResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.UserSettings.UserSettingsNotFound, result.FirstError);
_mockPlaybackDeliveryHandleService.DidNotReceive().IssueDeliveryId(Arg.Any<PlaybackDeliveryHandleDto>());
}
[Fact]
public async Task HandleAsync_WhenTheUserHasSettings_ShouldCaptureTheirStreamingQualityInTheDelivery()
{
// Arrange
GetPlaybackManifestQuery query = _getPlaybackManifestQueryFixture.Create();
TrackPlaybackManifestDto track = _trackPlaybackManifestDtoFixture.Create(path: _sourcePath);
UserSettingsEntity settings = _userSettingsEntityFixture.Create(userId: _userId, streamingQuality: PlaybackStreamingQuality.High);
StubNormalizedDelivery(query, track, settings: settings);
CaptureIssuedDelivery();
// Act
Result<PlaybackManifestResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.NotNull(_issuedDelivery);
Assert.Equal(PlaybackStreamingQuality.High, _issuedDelivery.Request.Quality);
}
[Fact]
public async Task HandleAsync_WhenTheLibraryCannotBeRead_ShouldReturnItsError()
{
// Arrange
GetPlaybackManifestQuery query = _getPlaybackManifestQueryFixture.Create();
Guid libraryId = Guid.Parse(query.LibraryId!);
TrackPlaybackManifestDto track = _trackPlaybackManifestDtoFixture.Create(path: _sourcePath);
StubTrackLookup(query, track);
StubNormalizedDecision();
_mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any<CancellationToken>()).Returns(Result.From<UserSettingsEntity?>(null));
_mockLibraryRepository.GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Errors.Library.LibraryIdCannotBeEmpty);
// Act
Result<PlaybackManifestResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError);
_mockPlaybackDeliveryHandleService.DidNotReceive().IssueDeliveryId(Arg.Any<PlaybackDeliveryHandleDto>());
}
[Fact]
public async Task HandleAsync_WhenTheLibraryIsNotFound_ShouldReturnLibraryNotFoundError()
{
// Arrange
GetPlaybackManifestQuery query = _getPlaybackManifestQueryFixture.Create();
Guid libraryId = Guid.Parse(query.LibraryId!);
TrackPlaybackManifestDto track = _trackPlaybackManifestDtoFixture.Create(path: _sourcePath);
StubTrackLookup(query, track);
StubNormalizedDecision();
_mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any<CancellationToken>()).Returns(Result.From<UserSettingsEntity?>(null));
_mockLibraryRepository.GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(null));
// Act
Result<PlaybackManifestResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.LibraryNotFound, result.FirstError);
_mockPlaybackDeliveryHandleService.DidNotReceive().IssueDeliveryId(Arg.Any<PlaybackDeliveryHandleDto>());
}
[Fact]
public async Task HandleAsync_WhenTheSourceFileIsInsideAContentLocation_ShouldCaptureItsIdentityInTheDelivery()
{
// Arrange
byte[] sourceBytes = new byte[1234];
await File.WriteAllBytesAsync(_sourcePath, sourceBytes);
DateTime sourceLastModifiedUtc = new(2026, 1, 2, 3, 4, 5, DateTimeKind.Utc);
File.SetLastWriteTimeUtc(_sourcePath, sourceLastModifiedUtc);
DateTime expectedLastModifiedUtc = File.GetLastWriteTimeUtc(_sourcePath);
GetPlaybackManifestQuery query = _getPlaybackManifestQueryFixture.Create();
TrackPlaybackManifestDto track = _trackPlaybackManifestDtoFixture.Create(path: _sourcePath);
StubNormalizedDelivery(query, track, settings: null);
CaptureIssuedDelivery();
// Act
Result<PlaybackManifestResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.NotNull(_issuedDelivery);
Assert.Equal(sourceBytes.Length, _issuedDelivery.Request.SourceLength);
Assert.Equal(expectedLastModifiedUtc, _issuedDelivery.Request.SourceLastModifiedUtc);
}
[Fact]
public async Task HandleAsync_WhenTheSourceFileIsOutsideEveryContentLocation_ShouldNotCaptureItsIdentity()
{
// Arrange
await File.WriteAllBytesAsync(_sourcePath, new byte[1234]);
GetPlaybackManifestQuery query = _getPlaybackManifestQueryFixture.Create();
TrackPlaybackManifestDto track = _trackPlaybackManifestDtoFixture.Create(path: _sourcePath);
StubNormalizedDelivery(query, track, settings: null);
CaptureIssuedDelivery();
_mockPathService.IsPathWithin(Arg.Any<string>(), Arg.Any<string>()).Returns(false);
// Act
Result<PlaybackManifestResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.NotNull(_issuedDelivery);
Assert.Equal(0, _issuedDelivery.Request.SourceLength);
Assert.Equal(DateTime.MinValue, _issuedDelivery.Request.SourceLastModifiedUtc);
}
[Fact]
public async Task HandleAsync_WhenANormalizedDeliveryIsIssued_ShouldIssueTheExactDeclaredDelivery()
{
// Arrange
GetPlaybackManifestQuery query = _getPlaybackManifestQueryFixture.Create(capabilities: "mp3/mp3,flac/flac");
Guid libraryId = Guid.Parse(query.LibraryId!);
Guid albumId = Guid.Parse(query.AlbumId!);
Guid artistId = Guid.Parse(query.ArtistId!);
Guid trackId = Guid.Parse(query.TrackId!);
TrackPlaybackManifestDto track = _trackPlaybackManifestDtoFixture.Create(
path: _sourcePath,
container: "FLAC",
audioCodec: "FLAC",
durationInSeconds: 245,
sampleRate: 48000,
channels: 2,
bitDepth: 24,
bitrate: 900);
PlaybackDeliveryDecisionDto decision = _playbackDeliveryDecisionDtoFixture.Create(
mode: PlaybackDeliveryMode.Transcode,
container: "MP3",
codec: "MP3",
shape: PlaybackDeliveryShape.TimeAddressedSegments,
segmentDurationSeconds: 6);
UserSettingsEntity settings = _userSettingsEntityFixture.Create(userId: _userId, streamingQuality: PlaybackStreamingQuality.High);
LibraryEntity library = _libraryEntityFixture.Create(id: libraryId, contentLocations: [_libraryRoot]);
StubTrackLookup(query, track);
_mockPlaybackFormatService.DecideDelivery(Arg.Any<PlaybackSourceFormatDto>(), Arg.Any<IReadOnlyList<PlaybackCapabilityDto>>())
.Returns(Result.From(decision));
_mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any<CancellationToken>()).Returns(Result.From<UserSettingsEntity?>(settings));
_mockLibraryRepository.GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(library));
CaptureIssuedDelivery();
// Act
Result<PlaybackManifestResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.NotNull(_issuedDelivery);
Assert.Equal(trackId, _issuedDelivery.Request.TrackId);
Assert.Equal(_userId, _issuedDelivery.Request.UserId);
Assert.Equal(PlaybackDeliveryMode.Transcode, _issuedDelivery.Request.Mode);
Assert.Equal("MP3", _issuedDelivery.Request.Container);
Assert.Equal("MP3", _issuedDelivery.Request.Codec);
Assert.Equal(6, _issuedDelivery.Request.SegmentDurationSeconds);
Assert.Equal(245, _issuedDelivery.Request.DurationInSeconds);
Assert.Equal(900, _issuedDelivery.Request.Bitrate);
Assert.Equal(48000, _issuedDelivery.Request.SampleRate);
Assert.Equal(2, _issuedDelivery.Request.Channels);
Assert.Equal(24, _issuedDelivery.Request.BitDepth);
Assert.Equal(PlaybackStreamingQuality.High, _issuedDelivery.Request.Quality);
Assert.Equal(_sourcePath, _issuedDelivery.Request.SourcePath);
Assert.Equal([_libraryRoot], _issuedDelivery.Request.AllowedRoots);
Assert.Equal(PlaybackDeliveryShape.TimeAddressedSegments, _issuedDelivery.Shape);
Assert.Equal(libraryId, _issuedDelivery.LibraryId);
Assert.Equal(albumId, _issuedDelivery.AlbumId);
Assert.Equal(artistId, _issuedDelivery.ArtistId);
_mockPlaybackFormatService.Received(1).DecideDelivery(
Arg.Is<PlaybackSourceFormatDto>(format => format.Container == "FLAC" && format.Codec == "FLAC"),
Arg.Is<IReadOnlyList<PlaybackCapabilityDto>>(capabilities => capabilities.Count == 2));
}
[Fact]
public async Task HandleAsync_WhenATimeAddressedDeliveryIsIssued_ShouldReturnItsDeliveryShapeAndSeekMap()
{
// Arrange
GetPlaybackManifestQuery query = _getPlaybackManifestQueryFixture.Create();
TrackPlaybackManifestDto track = _trackPlaybackManifestDtoFixture.Create(path: _sourcePath);
StubNormalizedDelivery(query, track, settings: null);
CaptureIssuedDelivery();
// Act
Result<PlaybackManifestResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.False(result.Value.IsDirectPlay);
Assert.Equal(PlaybackDeliveryShape.TimeAddressedSegments, result.Value.DeliveryShape);
Assert.Equal(6, result.Value.SegmentDurationSeconds);
Assert.True(result.Value.IsSeekable);
Assert.Equal(_issuedDeliveryId, result.Value.DeliveryId);
Assert.Equal(query.SegmentStreamPathTemplate, result.Value.SegmentStreamPathTemplate);
Assert.Equal(query.StreamPath, result.Value.StreamPath);
}
[Fact]
public async Task HandleAsync_WhenANonTimeAddressedDeliveryIsIssued_ShouldNotReportASegmentDuration()
{
// Arrange
GetPlaybackManifestQuery query = _getPlaybackManifestQueryFixture.Create();
TrackPlaybackManifestDto track = _trackPlaybackManifestDtoFixture.Create(path: _sourcePath);
PlaybackDeliveryDecisionDto decision = _playbackDeliveryDecisionDtoFixture.Create(
mode: PlaybackDeliveryMode.Remux,
container: "WAV",
codec: "PCM",
shape: PlaybackDeliveryShape.ByteRangeSeekable,
segmentDurationSeconds: 0);
StubTrackLookup(query, track);
_mockPlaybackFormatService.DecideDelivery(Arg.Any<PlaybackSourceFormatDto>(), Arg.Any<IReadOnlyList<PlaybackCapabilityDto>>())
.Returns(Result.From(decision));
StubSettings(null);
StubLibrary(Guid.Parse(query.LibraryId!));
CaptureIssuedDelivery();
// Act
Result<PlaybackManifestResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.False(result.Value.IsDirectPlay);
Assert.Equal(PlaybackDeliveryShape.ByteRangeSeekable, result.Value.DeliveryShape);
Assert.Null(result.Value.SegmentDurationSeconds);
Assert.True(result.Value.IsSeekable);
Assert.Equal(_issuedDeliveryId, result.Value.DeliveryId);
}
[Fact]
public async Task HandleAsync_WhenCancellationIsRequestedWhileLookingUpTheTrack_ShouldCancelTheOperation()
{
// Arrange
GetPlaybackManifestQuery query = _getPlaybackManifestQueryFixture.Create();
Guid libraryId = Guid.Parse(query.LibraryId!);
Guid albumId = Guid.Parse(query.AlbumId!);
Guid artistId = Guid.Parse(query.ArtistId!);
Guid trackId = Guid.Parse(query.TrackId!);
using CancellationTokenSource cancellationTokenSource = new();
cancellationTokenSource.Cancel();
_mockTrackRepository.GetPlaybackManifestInfoAsync(libraryId, albumId, artistId, trackId, cancellationTokenSource.Token)
.Returns(Task.FromCanceled<Result<TrackPlaybackManifestDto?>>(cancellationTokenSource.Token));
// Act & Assert
await Assert.ThrowsAsync<TaskCanceledException>(() => _sut.HandleAsync(query, cancellationTokenSource.Token));
await _mockTrackRepository.Received(1).GetPlaybackManifestInfoAsync(libraryId, albumId, artistId, trackId, cancellationTokenSource.Token);
}
/// <summary>
/// Stubs the track projection lookup of the query's route with the provided track.
/// </summary>
/// <param name="query">The query whose route identifiers are looked up.</param>
/// <param name="track">The track projection the lookup returns.</param>
private void StubTrackLookup(GetPlaybackManifestQuery query, TrackPlaybackManifestDto track)
{
_mockTrackRepository.GetPlaybackManifestInfoAsync(
Guid.Parse(query.LibraryId!),
Guid.Parse(query.AlbumId!),
Guid.Parse(query.ArtistId!),
Guid.Parse(query.TrackId!),
Arg.Any<CancellationToken>())
.Returns(Result.From<TrackPlaybackManifestDto?>(track));
}
/// <summary>
/// Stubs a non direct play delivery decision that produces time addressed six second segments.
/// </summary>
private void StubNormalizedDecision()
{
PlaybackDeliveryDecisionDto decision = _playbackDeliveryDecisionDtoFixture.Create(
mode: PlaybackDeliveryMode.Transcode,
container: "MP3",
codec: "MP3",
shape: PlaybackDeliveryShape.TimeAddressedSegments,
segmentDurationSeconds: 6);
_mockPlaybackFormatService.DecideDelivery(Arg.Any<PlaybackSourceFormatDto>(), Arg.Any<IReadOnlyList<PlaybackCapabilityDto>>())
.Returns(Result.From(decision));
}
/// <summary>
/// Stubs the user settings lookup with the provided settings, or with no settings when it is <see langword="null"/>.
/// </summary>
/// <param name="settings">The settings the lookup returns.</param>
private void StubSettings(UserSettingsEntity? settings)
{
_mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any<CancellationToken>()).Returns(Result.From(settings));
}
/// <summary>
/// Stubs the library lookup with a library that has the test source directory as its content location.
/// </summary>
/// <param name="libraryId">The Id of the library the lookup returns.</param>
private void StubLibrary(Guid libraryId)
{
LibraryEntity library = _libraryEntityFixture.Create(id: libraryId, contentLocations: [_libraryRoot]);
_mockLibraryRepository.GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(library));
}
/// <summary>
/// Stubs the complete non direct play chain of the handler.
/// </summary>
/// <param name="query">The query whose route identifiers are looked up.</param>
/// <param name="track">The track projection the lookup returns.</param>
/// <param name="settings">The settings the user settings lookup returns.</param>
private void StubNormalizedDelivery(GetPlaybackManifestQuery query, TrackPlaybackManifestDto track, UserSettingsEntity? settings)
{
StubTrackLookup(query, track);
StubNormalizedDecision();
StubSettings(settings);
StubLibrary(Guid.Parse(query.LibraryId!));
}
/// <summary>
/// Configures the delivery handle service so that the delivery it is asked to issue is captured and a fixed handle is returned.
/// </summary>
private void CaptureIssuedDelivery()
{
_mockPlaybackDeliveryHandleService.IssueDeliveryId(Arg.Do<PlaybackDeliveryHandleDto>(delivery => _issuedDelivery = delivery))
.Returns(_issuedDeliveryId);
}
/// <summary>
/// Releases the temporary directory the containment tests use.
/// </summary>
public void Dispose()
{
try
{
if (Directory.Exists(_sandboxRoot))
Directory.Delete(_sandboxRoot, recursive: true);
}
catch (IOException)
{
// A temporary directory that cannot be removed does not fail the test.
}
}
}
@@ -0,0 +1,411 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrackSegment;
using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrackSegment;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.SharedKernel.Common.Enums.Playback;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrackSegment;
/// <summary>
/// Contains unit tests for the <see cref="GetTrackSegmentQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetTrackSegmentQueryHandlerTests
{
private readonly ITrackNormalizationService _mockTrackNormalizationService;
private readonly IPlaybackDeliveryHandleService _mockPlaybackDeliveryHandleService;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IPathService _mockPathService;
private readonly IValidator<GetTrackSegmentQuery> _mockValidator;
private readonly GetTrackSegmentQueryHandler _sut;
private readonly Guid _userId;
private readonly string _allowedRoot;
private readonly GetTrackSegmentQueryFixture _getTrackSegmentQueryFixture = new();
private readonly PlaybackDeliveryHandleDtoFixture _playbackDeliveryHandleDtoFixture = new();
private readonly NormalizedTrackRequestDtoFixture _normalizedTrackRequestDtoFixture = new();
private readonly NormalizedTrackDtoFixture _normalizedTrackDtoFixture = new();
private readonly NormalizedTrackSegmentDtoFixture _normalizedTrackSegmentDtoFixture = new();
public static TheoryData<string> DeliveryMismatchCases => ["Library", "Album", "Artist"];
/// <summary>
/// Initializes a new instance of the <see cref="GetTrackSegmentQueryHandlerTests"/> class.
/// </summary>
public GetTrackSegmentQueryHandlerTests()
{
_mockTrackNormalizationService = Substitute.For<ITrackNormalizationService>();
_mockPlaybackDeliveryHandleService = Substitute.For<IPlaybackDeliveryHandleService>();
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockPathService = Substitute.For<IPathService>();
_mockValidator = Substitute.For<IValidator<GetTrackSegmentQuery>>();
_userId = Guid.NewGuid();
_allowedRoot = Path.Combine(Path.GetTempPath(), "lumina-tests", "music");
// Default stubs: the user is authenticated, the library ownership policy allows access, the query validates and the source path is inside an allowed root.
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
_mockValidator.Validate(Arg.Any<GetTrackSegmentQuery>()).Returns([]);
_mockPathService.IsPathWithin(Arg.Any<string>(), Arg.Any<string>()).Returns(true);
_sut = new GetTrackSegmentQueryHandler(
_mockTrackNormalizationService,
_mockPlaybackDeliveryHandleService,
_mockAuthorizationService,
_mockCurrentUserService,
_mockPathService,
_mockValidator);
}
[Fact]
public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutResolvingTheDelivery()
{
// Arrange
GetTrackSegmentQuery query = _getTrackSegmentQueryFixture.Create();
_mockValidator.Validate(Arg.Any<GetTrackSegmentQuery>()).Returns([Errors.Playback.SegmentIndexMustBeValid]);
// Act
Result<NormalizedTrackSegmentDataDto> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Playback.SegmentIndexMustBeValid, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
_mockPlaybackDeliveryHandleService.DidNotReceive().GetDelivery(Arg.Any<string?>(), Arg.Any<Guid>(), Arg.Any<Guid>());
await _mockTrackNormalizationService.DidNotReceive().GetOrCreateNormalizedTrackAsync(Arg.Any<NormalizedTrackRequestDto>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
GetTrackSegmentQuery query = _getTrackSegmentQueryFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<NormalizedTrackSegmentDataDto> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
_mockPlaybackDeliveryHandleService.DidNotReceive().GetDelivery(Arg.Any<string?>(), Arg.Any<Guid>(), Arg.Any<Guid>());
}
[Fact]
public async Task HandleAsync_WhenLibraryOwnershipIsDenied_ShouldReturnNotAuthorizedError()
{
// Arrange
GetTrackSegmentQuery query = _getTrackSegmentQueryFixture.Create();
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<NormalizedTrackSegmentDataDto> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
_mockPlaybackDeliveryHandleService.DidNotReceive().GetDelivery(Arg.Any<string?>(), Arg.Any<Guid>(), Arg.Any<Guid>());
await _mockTrackNormalizationService.DidNotReceive().GetOrCreateNormalizedTrackAsync(Arg.Any<NormalizedTrackRequestDto>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenTheDeliveryCannotBeResolved_ShouldReturnItsErrorWithoutProducingAudio()
{
// Arrange
GetTrackSegmentQuery query = _getTrackSegmentQueryFixture.Create();
Guid trackId = Guid.Parse(query.TrackId!);
_mockPlaybackDeliveryHandleService.GetDelivery(query.DeliveryId, _userId, trackId).Returns(Errors.Playback.PlaybackDeliveryNotFound);
// Act
Result<NormalizedTrackSegmentDataDto> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Playback.PlaybackDeliveryNotFound, result.FirstError);
await _mockTrackNormalizationService.DidNotReceive().GetOrCreateNormalizedTrackAsync(Arg.Any<NormalizedTrackRequestDto>(), Arg.Any<CancellationToken>());
}
[Theory]
[MemberData(nameof(DeliveryMismatchCases))]
public async Task HandleAsync_WhenTheDeliveryDoesNotDescribeTheRoute_ShouldReturnPlaybackDeliveryNotFoundError(string mismatch)
{
// Arrange
GetTrackSegmentQuery query = _getTrackSegmentQueryFixture.Create();
Guid trackId = Guid.Parse(query.TrackId!);
PlaybackDeliveryHandleDto delivery = CreateDelivery(query);
delivery = mismatch switch
{
"Library" => delivery with { LibraryId = Guid.NewGuid() },
"Album" => delivery with { AlbumId = Guid.NewGuid() },
_ => delivery with { ArtistId = Guid.NewGuid() }
};
_mockPlaybackDeliveryHandleService.GetDelivery(query.DeliveryId, _userId, trackId).Returns(Result.From(delivery));
// Act
Result<NormalizedTrackSegmentDataDto> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Playback.PlaybackDeliveryNotFound, result.FirstError);
await _mockTrackNormalizationService.DidNotReceive().GetOrCreateNormalizedTrackAsync(Arg.Any<NormalizedTrackRequestDto>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenTheDeliveryIsADirectPlay_ShouldReturnNormalizationIsNotRequiredForDirectPlayError()
{
// Arrange
GetTrackSegmentQuery query = _getTrackSegmentQueryFixture.Create();
Guid trackId = Guid.Parse(query.TrackId!);
PlaybackDeliveryHandleDto delivery = CreateDelivery(query, mode: PlaybackDeliveryMode.DirectPlay);
_mockPlaybackDeliveryHandleService.GetDelivery(query.DeliveryId, _userId, trackId).Returns(Result.From(delivery));
// Act
Result<NormalizedTrackSegmentDataDto> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Playback.NormalizationIsNotRequiredForDirectPlay, result.FirstError);
await _mockTrackNormalizationService.DidNotReceive().GetOrCreateNormalizedTrackAsync(Arg.Any<NormalizedTrackRequestDto>(), Arg.Any<CancellationToken>());
}
public static TheoryData<PlaybackDeliveryShape, int> NonSegmentDeliveryCases => new()
{
{ PlaybackDeliveryShape.ByteRangeSeekable, 6 }, // a byte range delivery has no indexable segment
{ PlaybackDeliveryShape.TimeAddressedSegments, 0 } // a time addressed delivery without a positive segment duration has nothing to index
};
[Theory]
[MemberData(nameof(NonSegmentDeliveryCases))]
public async Task HandleAsync_WhenTheDeliveryIsNotAddressedAsTimeAddressedSegments_ShouldReturnPlaybackDeliveryChangedError(PlaybackDeliveryShape shape, int segmentDurationSeconds)
{
// Arrange
GetTrackSegmentQuery query = _getTrackSegmentQueryFixture.Create();
Guid trackId = Guid.Parse(query.TrackId!);
PlaybackDeliveryHandleDto delivery = CreateDelivery(query, shape: shape, segmentDurationSeconds: segmentDurationSeconds);
_mockPlaybackDeliveryHandleService.GetDelivery(query.DeliveryId, _userId, trackId).Returns(Result.From(delivery));
// Act
Result<NormalizedTrackSegmentDataDto> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Playback.PlaybackDeliveryChanged, result.FirstError);
await _mockTrackNormalizationService.DidNotReceive().GetOrCreateNormalizedTrackAsync(Arg.Any<NormalizedTrackRequestDto>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenTheSourcePathIsOutsideEveryAllowedRoot_ShouldReturnTrackFileNotFoundError()
{
// Arrange
GetTrackSegmentQuery query = _getTrackSegmentQueryFixture.Create();
Guid trackId = Guid.Parse(query.TrackId!);
PlaybackDeliveryHandleDto delivery = CreateDelivery(query);
_mockPlaybackDeliveryHandleService.GetDelivery(query.DeliveryId, _userId, trackId).Returns(Result.From(delivery));
_mockPathService.IsPathWithin(Arg.Any<string>(), Arg.Any<string>()).Returns(false);
// Act
Result<NormalizedTrackSegmentDataDto> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.TrackFileNotFound, result.FirstError);
await _mockTrackNormalizationService.DidNotReceive().GetOrCreateNormalizedTrackAsync(Arg.Any<NormalizedTrackRequestDto>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenNormalizationFails_ShouldReturnItsErrorWithoutOpeningASegment()
{
// Arrange
GetTrackSegmentQuery query = _getTrackSegmentQueryFixture.Create();
Guid trackId = Guid.Parse(query.TrackId!);
PlaybackDeliveryHandleDto delivery = CreateDelivery(query);
_mockPlaybackDeliveryHandleService.GetDelivery(query.DeliveryId, _userId, trackId).Returns(Result.From(delivery));
_mockTrackNormalizationService.GetOrCreateNormalizedTrackAsync(delivery.Request, Arg.Any<CancellationToken>())
.Returns(Errors.Playback.NormalizationFailed);
// Act
Result<NormalizedTrackSegmentDataDto> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Playback.NormalizationFailed, result.FirstError);
_mockTrackNormalizationService.DidNotReceive().OpenNormalizedSegment(Arg.Any<string>(), Arg.Any<Guid>(), Arg.Any<int>());
}
[Fact]
public async Task HandleAsync_WhenTheNormalizedTrackHasNoRequestedSegment_ShouldReturnNormalizedTrackSegmentNotFoundError()
{
// Arrange
GetTrackSegmentQuery query = _getTrackSegmentQueryFixture.Create(segmentIndex: "5");
Guid trackId = Guid.Parse(query.TrackId!);
PlaybackDeliveryHandleDto delivery = CreateDelivery(query);
NormalizedTrackDto normalizedTrack = _normalizedTrackDtoFixture.Create(
trackId: trackId,
segments: [_normalizedTrackSegmentDtoFixture.Create(index: 0)]);
_mockPlaybackDeliveryHandleService.GetDelivery(query.DeliveryId, _userId, trackId).Returns(Result.From(delivery));
_mockTrackNormalizationService.GetOrCreateNormalizedTrackAsync(delivery.Request, Arg.Any<CancellationToken>())
.Returns(Result.From(normalizedTrack));
// Act
Result<NormalizedTrackSegmentDataDto> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Playback.NormalizedTrackSegmentNotFound, result.FirstError);
_mockTrackNormalizationService.DidNotReceive().OpenNormalizedSegment(Arg.Any<string>(), Arg.Any<Guid>(), Arg.Any<int>());
}
[Fact]
public async Task HandleAsync_WhenTheSegmentCannotBeOpened_ShouldReturnItsError()
{
// Arrange
GetTrackSegmentQuery query = _getTrackSegmentQueryFixture.Create(segmentIndex: "0");
Guid trackId = Guid.Parse(query.TrackId!);
PlaybackDeliveryHandleDto delivery = CreateDelivery(query);
NormalizedTrackDto normalizedTrack = _normalizedTrackDtoFixture.Create(
trackId: trackId,
segments: [_normalizedTrackSegmentDtoFixture.Create(index: 0)]);
_mockPlaybackDeliveryHandleService.GetDelivery(query.DeliveryId, _userId, trackId).Returns(Result.From(delivery));
_mockTrackNormalizationService.GetOrCreateNormalizedTrackAsync(delivery.Request, Arg.Any<CancellationToken>())
.Returns(Result.From(normalizedTrack));
_mockTrackNormalizationService.OpenNormalizedSegment(normalizedTrack.CacheId, trackId, 0)
.Returns(Errors.Playback.NormalizedTrackCacheEntryNotFound);
// Act
Result<NormalizedTrackSegmentDataDto> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Playback.NormalizedTrackCacheEntryNotFound, result.FirstError);
}
[Fact]
public async Task HandleAsync_WhenSuccessful_ShouldReturnTheSegmentDataOfTheProducedTrack()
{
// Arrange
GetTrackSegmentQuery query = _getTrackSegmentQueryFixture.Create(segmentIndex: "2");
Guid trackId = Guid.Parse(query.TrackId!);
PlaybackDeliveryHandleDto delivery = CreateDelivery(query);
NormalizedTrackSegmentDto segment = _normalizedTrackSegmentDtoFixture.Create(index: 2, startSeconds: 12.5m, durationSeconds: 6m, length: 4096);
NormalizedTrackDto normalizedTrack = _normalizedTrackDtoFixture.Create(
trackId: trackId,
container: "MP3",
segmentDurationSeconds: 6,
durationInSeconds: 121,
segments: [_normalizedTrackSegmentDtoFixture.Create(index: 0), _normalizedTrackSegmentDtoFixture.Create(index: 1), segment]);
MemoryStream stream = new([1, 2, 3, 4]);
_mockPlaybackDeliveryHandleService.GetDelivery(query.DeliveryId, _userId, trackId).Returns(Result.From(delivery));
_mockTrackNormalizationService.GetOrCreateNormalizedTrackAsync(delivery.Request, Arg.Any<CancellationToken>())
.Returns(Result.From(normalizedTrack));
_mockTrackNormalizationService.OpenNormalizedSegment(normalizedTrack.CacheId, trackId, 2)
.Returns(Result<Stream>.Success(stream));
// Act
Result<NormalizedTrackSegmentDataDto> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Same(stream, result.Value.Content);
Assert.Equal(segment.Length, result.Value.Length);
Assert.Equal(segment.StartSeconds, result.Value.StartSeconds);
Assert.Equal(normalizedTrack.Container, result.Value.Container);
Assert.Equal(normalizedTrack.Segments.Count, result.Value.SegmentCount);
Assert.Equal(normalizedTrack.DurationInSeconds, result.Value.DurationInSeconds);
}
[Fact]
public async Task HandleAsync_WhenSuccessful_ShouldNormalizeTheDeliveryRequestAndOpenTheRequestedSegment()
{
// Arrange
GetTrackSegmentQuery query = _getTrackSegmentQueryFixture.Create(segmentIndex: "3");
Guid trackId = Guid.Parse(query.TrackId!);
PlaybackDeliveryHandleDto delivery = CreateDelivery(query);
NormalizedTrackSegmentDto segment = _normalizedTrackSegmentDtoFixture.Create(index: 3);
NormalizedTrackDto normalizedTrack = _normalizedTrackDtoFixture.Create(
trackId: trackId,
segmentDurationSeconds: 6,
segments: [_normalizedTrackSegmentDtoFixture.Create(index: 3)]);
_mockPlaybackDeliveryHandleService.GetDelivery(query.DeliveryId, _userId, trackId).Returns(Result.From(delivery));
_mockTrackNormalizationService.GetOrCreateNormalizedTrackAsync(Arg.Any<NormalizedTrackRequestDto>(), Arg.Any<CancellationToken>())
.Returns(Result.From(normalizedTrack));
_mockTrackNormalizationService.OpenNormalizedSegment(Arg.Any<string>(), Arg.Any<Guid>(), Arg.Any<int>())
.Returns(Result<Stream>.Success(new MemoryStream()));
// Act
await _sut.HandleAsync(query, CancellationToken.None);
// Assert
await _mockTrackNormalizationService.Received(1).GetOrCreateNormalizedTrackAsync(
Arg.Is<NormalizedTrackRequestDto>(request => ReferenceEquals(request, delivery.Request)),
Arg.Any<CancellationToken>());
_mockTrackNormalizationService.Received(1).OpenNormalizedSegment(normalizedTrack.CacheId, trackId, segment.Index);
}
[Fact]
public async Task HandleAsync_WhenCancellationIsRequestedWhileNormalizing_ShouldCancelTheOperation()
{
// Arrange
GetTrackSegmentQuery query = _getTrackSegmentQueryFixture.Create(segmentIndex: "0");
Guid trackId = Guid.Parse(query.TrackId!);
PlaybackDeliveryHandleDto delivery = CreateDelivery(query);
using CancellationTokenSource cancellationTokenSource = new();
cancellationTokenSource.Cancel();
_mockPlaybackDeliveryHandleService.GetDelivery(query.DeliveryId, _userId, trackId).Returns(Result.From(delivery));
_mockTrackNormalizationService.GetOrCreateNormalizedTrackAsync(delivery.Request, cancellationTokenSource.Token)
.Returns(Task.FromCanceled<Result<NormalizedTrackDto>>(cancellationTokenSource.Token));
// Act & Assert
await Assert.ThrowsAsync<TaskCanceledException>(() => _sut.HandleAsync(query, cancellationTokenSource.Token));
await _mockTrackNormalizationService.Received(1).GetOrCreateNormalizedTrackAsync(delivery.Request, cancellationTokenSource.Token);
}
/// <summary>
/// Creates a delivery that matches the library, album, artist and track named by the provided query.
/// </summary>
/// <param name="query">The query whose route identifiers the delivery must describe.</param>
/// <param name="mode">The way the audio is delivered.</param>
/// <param name="shape">The shape the delivered audio is addressed by.</param>
/// <param name="segmentDurationSeconds">The duration of each segment of the delivered audio, in seconds.</param>
/// <returns>The created delivery.</returns>
private PlaybackDeliveryHandleDto CreateDelivery(
GetTrackSegmentQuery query,
PlaybackDeliveryMode mode = PlaybackDeliveryMode.Transcode,
PlaybackDeliveryShape shape = PlaybackDeliveryShape.TimeAddressedSegments,
int segmentDurationSeconds = 6)
{
return _playbackDeliveryHandleDtoFixture.Create(
request: _normalizedTrackRequestDtoFixture.Create(
trackId: Guid.Parse(query.TrackId!),
userId: _userId,
sourcePath: Path.Combine(_allowedRoot, "track.flac"),
allowedRoots: [_allowedRoot],
mode: mode,
segmentDurationSeconds: segmentDurationSeconds,
durationInSeconds: 120),
shape: shape,
libraryId: Guid.Parse(query.LibraryId!),
albumId: Guid.Parse(query.AlbumId!),
artistId: Guid.Parse(query.ArtistId!));
}
}
@@ -0,0 +1,218 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrackSegment;
using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrackSegment;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrackSegment;
/// <summary>
/// Contains unit tests for the <see cref="GetTrackSegmentQueryValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetTrackSegmentQueryValidatorTests
{
private const string VALID_DELIVERY_ID = "0123456789abcdef0123456789abcdef";
private readonly GetTrackSegmentQueryFixture _getTrackSegmentQueryFixture = new();
private readonly GetTrackSegmentQueryValidator _validator = new();
[Fact]
public void Validate_WhenQueryIsValid_ShouldNotHaveAnyValidationError()
{
// Arrange
GetTrackSegmentQuery query = _getTrackSegmentQueryFixture.Create(deliveryId: VALID_DELIVERY_ID, segmentIndex: "0");
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
[Theory]
[InlineData(null)] // missing route value
[InlineData("")] // empty route value
[InlineData(" ")] // whitespace route value
[InlineData("not-a-library-guid")] // non-Guid route value
[InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value
public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveLibraryIdError(string? libraryId)
{
// Arrange
GetTrackSegmentQuery query = _getTrackSegmentQueryFixture.Create(libraryId: libraryId, includeLibraryId: libraryId is not null);
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
}
[Theory]
[InlineData(null)] // missing route value
[InlineData("")] // empty route value
[InlineData(" ")] // whitespace route value
[InlineData("not-an-artist-guid")] // non-Guid route value
[InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value
public void Validate_WhenArtistIdIsEmptyOrInvalid_ShouldHaveArtistIdError(string? artistId)
{
// Arrange
GetTrackSegmentQuery query = _getTrackSegmentQueryFixture.Create(artistId: artistId, includeArtistId: artistId is not null);
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty);
}
[Theory]
[InlineData(null)] // missing route value
[InlineData("")] // empty route value
[InlineData(" ")] // whitespace route value
[InlineData("not-an-album-guid")] // non-Guid route value
[InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value
public void Validate_WhenAlbumIdIsEmptyOrInvalid_ShouldHaveAlbumIdError(string? albumId)
{
// Arrange
GetTrackSegmentQuery query = _getTrackSegmentQueryFixture.Create(albumId: albumId, includeAlbumId: albumId is not null);
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty);
}
[Theory]
[InlineData(null)] // missing route value
[InlineData("")] // empty route value
[InlineData(" ")] // whitespace route value
[InlineData("not-a-track-guid")] // non-Guid route value
[InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value
public void Validate_WhenTrackIdIsEmptyOrInvalid_ShouldHaveTrackIdError(string? trackId)
{
// Arrange
GetTrackSegmentQuery query = _getTrackSegmentQueryFixture.Create(trackId: trackId, includeTrackId: trackId is not null);
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Music.TrackIdCannotBeEmpty);
}
[Theory]
[InlineData(null)] // missing route value
[InlineData("")] // empty route value
[InlineData(" ")] // whitespace route value
public void Validate_WhenDeliveryIdIsEmpty_ShouldHaveDeliveryIdCannotBeEmptyError(string? deliveryId)
{
// Arrange
GetTrackSegmentQuery query = _getTrackSegmentQueryFixture.Create(deliveryId: deliveryId, includeDeliveryId: deliveryId is not null);
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Playback.DeliveryIdCannotBeEmpty);
}
[Theory]
[InlineData("0123456789ABCDEF0123456789ABCDEF")] // uppercase hexadecimal is not the canonical lowercase handle
[InlineData("01234567-89ab-cdef-0123-456789abcdef")] // the D format of a Guid carries dashes
[InlineData("0123456789abcdef0123456789abcde")] // 31 characters, one short of a handle
[InlineData("0123456789abcdef0123456789abcdef0")] // 33 characters, one over a handle
[InlineData("0123456789abcdef0123456789abcdeg")] // the last character is not a hexadecimal digit
public void Validate_WhenDeliveryIdShapeIsInvalid_ShouldHaveDeliveryIdIsInvalidError(string deliveryId)
{
// Arrange
GetTrackSegmentQuery query = _getTrackSegmentQueryFixture.Create(deliveryId: deliveryId);
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Playback.DeliveryIdIsInvalid);
}
[Theory]
[InlineData(null)] // missing route value
[InlineData("")] // empty route value
[InlineData(" ")] // whitespace route value
public void Validate_WhenSegmentIndexIsEmpty_ShouldHaveSegmentIndexCannotBeEmptyError(string? segmentIndex)
{
// Arrange
GetTrackSegmentQuery query = _getTrackSegmentQueryFixture.Create(deliveryId: VALID_DELIVERY_ID, segmentIndex: segmentIndex, includeSegmentIndex: segmentIndex is not null);
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Playback.SegmentIndexCannotBeEmpty);
}
[Theory]
[InlineData("-1")] // a negative index does not address a segment
[InlineData("abc")] // a non-numeric index does not address a segment
[InlineData("1.5")] // a fractional index does not address a segment
[InlineData("2147483648")] // a value above the range of an integer
public void Validate_WhenSegmentIndexIsNotANonNegativeInteger_ShouldHaveSegmentIndexMustBeValidError(string segmentIndex)
{
// Arrange
GetTrackSegmentQuery query = _getTrackSegmentQueryFixture.Create(deliveryId: VALID_DELIVERY_ID, segmentIndex: segmentIndex);
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Playback.SegmentIndexMustBeValid);
}
[Theory]
[InlineData("0")] // the first segment of the audio
[InlineData("2147483647")] // the largest index an integer can address
public void Validate_WhenSegmentIndexIsANonNegativeInteger_ShouldNotHaveSegmentIndexMustBeValidError(string segmentIndex)
{
// Arrange
GetTrackSegmentQuery query = _getTrackSegmentQueryFixture.Create(deliveryId: VALID_DELIVERY_ID, segmentIndex: segmentIndex);
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationError(Errors.Playback.SegmentIndexMustBeValid);
result.ShouldNotHaveValidationError(Errors.Playback.SegmentIndexCannotBeEmpty);
}
[Fact]
public void Validate_WhenSeveralFieldsAreInvalid_ShouldReportEachSpecificError()
{
// Arrange
GetTrackSegmentQuery query = _getTrackSegmentQueryFixture.Create(
libraryId: "not-a-library-guid",
artistId: null,
includeArtistId: false,
albumId: Guid.Empty.ToString(),
trackId: "not-a-track-guid",
deliveryId: "0123456789ABCDEF0123456789ABCDEF",
segmentIndex: "-1");
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty);
result.ShouldHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty);
result.ShouldHaveValidationError(Errors.Music.TrackIdCannotBeEmpty);
result.ShouldHaveValidationError(Errors.Playback.DeliveryIdIsInvalid);
result.ShouldHaveValidationError(Errors.Playback.SegmentIndexMustBeValid);
Assert.Equal(6, result.Count);
}
}
@@ -0,0 +1,454 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration;
using Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.Configuration;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Path;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform;
using Lumina.Infrastructure.Common.Errors;
using Lumina.Infrastructure.Common.Models.DTO.Configuration;
using Lumina.Infrastructure.Common.Validators;
using Lumina.Infrastructure.Fixtures.Common.Models.DTO.Configuration;
using Microsoft.Extensions.Options;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.IO.Abstractions;
#endregion
namespace Lumina.Infrastructure.UnitTests.Common.Validators;
/// <summary>
/// Contains unit tests for the <see cref="TranscodingSettingsDtoValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class TranscodingSettingsDtoValidatorTests : IDisposable
{
private readonly TranscodingSettingsDtoValidator _validator;
private readonly TranscodingSettingsDtoFixture _transcodingSettingsDtoFixture = new();
private readonly MediaSettingsDtoFixture _mediaSettingsDtoFixture = new();
private readonly PluginsSettingsDtoFixture _pluginsSettingsDtoFixture = new();
private readonly string _sandboxRoot;
private readonly string _mediaRoot;
private readonly string _validCacheDirectory;
private readonly string _pluginsDirectory;
/// <summary>
/// Initializes a new instance of the <see cref="TranscodingSettingsDtoValidatorTests"/> class.
/// </summary>
public TranscodingSettingsDtoValidatorTests()
{
_sandboxRoot = Path.Combine(Path.GetTempPath(), "lumina-transcoding-validator-tests-" + Guid.NewGuid().ToString("N"));
_mediaRoot = Path.Combine(_sandboxRoot, "media");
_validCacheDirectory = Path.Combine(_sandboxRoot, "cache");
_pluginsDirectory = Path.Combine(_sandboxRoot, "plugins");
Directory.CreateDirectory(_mediaRoot);
Directory.CreateDirectory(_validCacheDirectory);
Directory.CreateDirectory(_pluginsDirectory);
// The real path service is used, with the real path strategy of the current platform, so containment follows the file system rules of the host.
IPlatformContext platformContext = Substitute.For<IPlatformContext>();
IPathStrategy pathStrategy = OperatingSystem.IsWindows()
? new WindowsPathStrategy(new FileSystem())
: new UnixPathStrategy(new FileSystem());
platformContext.PathStrategy.Returns(pathStrategy);
IPlatformContextManager platformContextManager = Substitute.For<IPlatformContextManager>();
platformContextManager.GetCurrentContext().Returns(platformContext);
IPathService pathService = new PathService(platformContextManager);
// An absolute root directory pins the media root that is served by the media route, because Path.Combine returns its second argument when it is rooted.
MediaSettingsDto mediaSettings = _mediaSettingsDtoFixture.Create(rootDirectory: _mediaRoot);
PluginsSettingsDto pluginsSettings = _pluginsSettingsDtoFixture.Create(directory: _pluginsDirectory);
_validator = new TranscodingSettingsDtoValidator(Options.Create(mediaSettings), Options.Create(pluginsSettings), pathService);
}
[Fact]
public void Validate_WhenSettingsAreValid_ShouldNotHaveAnyValidationError()
{
// Arrange
TranscodingSettingsDto model = CreateSettings();
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Empty(result);
}
[Theory]
[InlineData(null)] // a missing ffmpeg path
[InlineData("")] // an empty ffmpeg path
[InlineData(" ")] // a whitespace ffmpeg path
public void Validate_WhenFfmpegPathIsEmpty_ShouldHaveFfmpegPathCannotBeEmptyError(string? ffmpegPath)
{
// Arrange
TranscodingSettingsDto model = CreateSettings(ffmpegPath: ffmpegPath, includeFfmpegPath: ffmpegPath is not null);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingFfmpegPathCannotBeEmpty.Description);
}
[Theory]
[InlineData(0)] // a job count of zero disables normalization
[InlineData(-1)] // a negative job count disables normalization
public void Validate_WhenMaxConcurrentJobsIsNotPositive_ShouldHaveMaxConcurrentJobsMustBePositiveError(int maxConcurrentJobs)
{
// Arrange
TranscodingSettingsDto model = CreateSettings(maxConcurrentJobs: maxConcurrentJobs, maxConcurrentJobsPerUser: 1);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingMaxConcurrentJobsMustBePositive.Description);
}
[Fact]
public void Validate_WhenMaxConcurrentJobsIsTooLarge_ShouldHaveMaxConcurrentJobsIsTooLargeError()
{
// Arrange
TranscodingSettingsDto model = CreateSettings(maxConcurrentJobs: 65, maxConcurrentJobsPerUser: 1);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingMaxConcurrentJobsIsTooLarge.Description);
}
[Fact]
public void Validate_WhenMaxConcurrentJobsIsTheMaximum_ShouldNotHaveMaxConcurrentJobsErrors()
{
// Arrange
TranscodingSettingsDto model = CreateSettings(maxConcurrentJobs: 64, maxConcurrentJobsPerUser: 64);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.DoesNotContain(result, error => error.Description == Errors.Configuration.TranscodingMaxConcurrentJobsIsTooLarge.Description);
Assert.DoesNotContain(result, error => error.Description == Errors.Configuration.TranscodingMaxConcurrentJobsMustBePositive.Description);
}
[Theory]
[InlineData(0)] // a per-user job count of zero never admits a normalization
[InlineData(-1)] // a negative per-user job count never admits a normalization
public void Validate_WhenMaxConcurrentJobsPerUserIsNotPositive_ShouldHaveMaxConcurrentJobsPerUserMustBePositiveError(int maxConcurrentJobsPerUser)
{
// Arrange
TranscodingSettingsDto model = CreateSettings(maxConcurrentJobs: 8, maxConcurrentJobsPerUser: maxConcurrentJobsPerUser);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingMaxConcurrentJobsPerUserMustBePositive.Description);
}
[Fact]
public void Validate_WhenMaxConcurrentJobsPerUserIsTooLarge_ShouldHaveMaxConcurrentJobsPerUserIsTooLargeError()
{
// Arrange
TranscodingSettingsDto model = CreateSettings(maxConcurrentJobs: 64, maxConcurrentJobsPerUser: 65);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingMaxConcurrentJobsPerUserIsTooLarge.Description);
}
[Fact]
public void Validate_WhenMaxConcurrentJobsPerUserExceedsTheGlobalLimit_ShouldHaveMaxConcurrentJobsPerUserExceedsGlobalError()
{
// Arrange
TranscodingSettingsDto model = CreateSettings(maxConcurrentJobs: 8, maxConcurrentJobsPerUser: 16);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingMaxConcurrentJobsPerUserExceedsGlobal.Description);
Assert.DoesNotContain(result, error => error.Description == Errors.Configuration.TranscodingMaxConcurrentJobsPerUserIsTooLarge.Description);
}
[Theory]
[InlineData(0)] // a cache with no capacity cannot hold a normalized track
[InlineData(-1)] // a negative cache size is not a capacity
public void Validate_WhenMaxCacheBytesIsNotPositive_ShouldHaveMaxCacheBytesMustBePositiveError(long maxCacheBytes)
{
// Arrange
TranscodingSettingsDto model = CreateSettings(maxCacheBytes: maxCacheBytes);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingMaxCacheBytesMustBePositive.Description);
}
[Theory]
[InlineData(0)] // a job timeout of zero stops every job immediately
[InlineData(-1)] // a negative job timeout stops every job immediately
public void Validate_WhenJobTimeoutSecondsIsNotPositive_ShouldHaveJobTimeoutMustBePositiveError(int jobTimeoutSeconds)
{
// Arrange
TranscodingSettingsDto model = CreateSettings(jobTimeoutSeconds: jobTimeoutSeconds);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingJobTimeoutMustBePositive.Description);
}
[Fact]
public void Validate_WhenJobTimeoutSecondsIsTooLong_ShouldHaveJobTimeoutIsTooLongError()
{
// Arrange
TranscodingSettingsDto model = CreateSettings(jobTimeoutSeconds: 86_401);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingJobTimeoutIsTooLong.Description);
}
[Fact]
public void Validate_WhenJobTimeoutSecondsIsTheMaximum_ShouldNotHaveJobTimeoutErrors()
{
// Arrange
TranscodingSettingsDto model = CreateSettings(jobTimeoutSeconds: 86_400);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.DoesNotContain(result, error => error.Description == Errors.Configuration.TranscodingJobTimeoutIsTooLong.Description);
Assert.DoesNotContain(result, error => error.Description == Errors.Configuration.TranscodingJobTimeoutMustBePositive.Description);
}
[Theory]
[InlineData(0)] // an eviction grace of zero protects nothing
[InlineData(-1)] // a negative eviction grace protects nothing
public void Validate_WhenEvictionGraceSecondsIsNotPositive_ShouldHaveEvictionGraceSecondsMustBePositiveError(int evictionGraceSeconds)
{
// Arrange
TranscodingSettingsDto model = CreateSettings(evictionGraceSeconds: evictionGraceSeconds);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingEvictionGraceSecondsMustBePositive.Description);
}
[Fact]
public void Validate_WhenEvictionGraceSecondsIsTooLong_ShouldHaveEvictionGraceSecondsIsTooLongError()
{
// Arrange
TranscodingSettingsDto model = CreateSettings(evictionGraceSeconds: 86_401);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingEvictionGraceSecondsIsTooLong.Description);
}
[Fact]
public void Validate_WhenEvictionGraceSecondsIsTheMaximum_ShouldNotHaveEvictionGraceSecondsErrors()
{
// Arrange
TranscodingSettingsDto model = CreateSettings(evictionGraceSeconds: 86_400);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.DoesNotContain(result, error => error.Description == Errors.Configuration.TranscodingEvictionGraceSecondsIsTooLong.Description);
Assert.DoesNotContain(result, error => error.Description == Errors.Configuration.TranscodingEvictionGraceSecondsMustBePositive.Description);
}
[Fact]
public void Validate_WhenCacheDirectoryIsMalformed_ShouldHaveCacheDirectoryIsInvalidError()
{
// Arrange
TranscodingSettingsDto model = CreateSettings(cacheDirectory: "bad\0path");
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingCacheDirectoryIsInvalid.Description);
Assert.DoesNotContain(result, error => error.Description == Errors.Configuration.TranscodingCacheDirectoryIsInsideMediaRoot.Description);
Assert.DoesNotContain(result, error => error.Description == Errors.Configuration.TranscodingCacheDirectoryContainsMediaRoot.Description);
Assert.DoesNotContain(result, error => error.Description == Errors.Configuration.TranscodingCacheDirectoryIsUnsafeLocation.Description);
}
[Fact]
public void Validate_WhenCacheDirectoryIsInsideTheMediaRoot_ShouldHaveCacheDirectoryIsInsideMediaRootError()
{
// Arrange
TranscodingSettingsDto model = CreateSettings(cacheDirectory: Path.Combine(_mediaRoot, "cache"));
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingCacheDirectoryIsInsideMediaRoot.Description);
Assert.DoesNotContain(result, error => error.Description == Errors.Configuration.TranscodingCacheDirectoryContainsMediaRoot.Description);
}
[Fact]
public void Validate_WhenCacheDirectoryContainsTheMediaRoot_ShouldHaveCacheDirectoryContainsMediaRootError()
{
// Arrange
TranscodingSettingsDto model = CreateSettings(cacheDirectory: _sandboxRoot);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingCacheDirectoryContainsMediaRoot.Description);
Assert.DoesNotContain(result, error => error.Description == Errors.Configuration.TranscodingCacheDirectoryIsInsideMediaRoot.Description);
}
[Fact]
public void Validate_WhenCacheDirectoryIsAFileSystemRoot_ShouldHaveCacheDirectoryIsUnsafeLocationError()
{
// Arrange
TranscodingSettingsDto model = CreateSettings(cacheDirectory: Path.GetPathRoot(_mediaRoot)!);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingCacheDirectoryIsUnsafeLocation.Description);
}
[Fact]
public void Validate_WhenCacheDirectoryIsTheApplicationBaseDirectory_ShouldHaveCacheDirectoryIsUnsafeLocationError()
{
// Arrange
TranscodingSettingsDto model = CreateSettings(cacheDirectory: AppContext.BaseDirectory);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingCacheDirectoryIsUnsafeLocation.Description);
}
[Fact]
public void Validate_WhenCacheDirectoryIsTheLogsDirectory_ShouldHaveCacheDirectoryIsUnsafeLocationError()
{
// Arrange
TranscodingSettingsDto model = CreateSettings(cacheDirectory: Path.Combine(AppContext.BaseDirectory, "logs"));
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingCacheDirectoryIsUnsafeLocation.Description);
}
[Fact]
public void Validate_WhenCacheDirectoryIsThePluginsDirectory_ShouldHaveCacheDirectoryIsUnsafeLocationError()
{
// Arrange
TranscodingSettingsDto model = CreateSettings(cacheDirectory: _pluginsDirectory);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingCacheDirectoryIsUnsafeLocation.Description);
}
[Fact]
public void Validate_WhenCacheDirectoryIsAValidExternalDirectory_ShouldNotHaveCacheDirectoryErrors()
{
// Arrange
TranscodingSettingsDto model = CreateSettings(cacheDirectory: _validCacheDirectory);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Empty(result);
}
[Theory]
[InlineData(null)] // no configured directory, so the default temporary directory is used
[InlineData(" ")] // a whitespace directory, so the default temporary directory is used
public void Validate_WhenCacheDirectoryIsNotConfigured_ShouldOnlyValidateTheDefaultDirectory(string? cacheDirectory)
{
// Arrange
TranscodingSettingsDto model = CreateSettings(cacheDirectory: cacheDirectory, includeCacheDirectory: cacheDirectory is not null);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Empty(result);
}
/// <summary>
/// Releases the temporary directories the containment tests use.
/// </summary>
public void Dispose()
{
try
{
if (Directory.Exists(_sandboxRoot))
Directory.Delete(_sandboxRoot, recursive: true);
}
catch (IOException)
{
// A temporary directory that cannot be removed does not fail the test.
}
}
/// <summary>
/// Creates settings that are valid unless an argument overrides a single rule under test.
/// </summary>
/// <param name="ffmpegPath">The file name or path of the ffmpeg binary.</param>
/// <param name="maxConcurrentJobs">The maximum number of normalization jobs that may run at the same time.</param>
/// <param name="maxConcurrentJobsPerUser">The maximum number of normalization jobs a single user may have running at the same time.</param>
/// <param name="maxCacheBytes">The maximum total size of the normalized audio cache, in bytes.</param>
/// <param name="jobTimeoutSeconds">The maximum duration of a single normalization job, in seconds.</param>
/// <param name="evictionGraceSeconds">The period during which a cache entry is protected from eviction, in seconds.</param>
/// <param name="cacheDirectory">The directory where normalized audio is cached.</param>
/// <param name="includeCacheDirectory">Whether the cache directory should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeFfmpegPath">Whether the ffmpeg path should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created settings.</returns>
private TranscodingSettingsDto CreateSettings(
string? ffmpegPath = "ffmpeg",
int? maxConcurrentJobs = 8,
int? maxConcurrentJobsPerUser = 4,
long? maxCacheBytes = 2L * 1024 * 1024 * 1024,
int? jobTimeoutSeconds = 900,
int? evictionGraceSeconds = 120,
string? cacheDirectory = null,
bool includeCacheDirectory = true,
bool includeFfmpegPath = true)
{
return _transcodingSettingsDtoFixture.Create(
ffmpegPath: ffmpegPath,
maxConcurrentJobs: maxConcurrentJobs,
maxConcurrentJobsPerUser: maxConcurrentJobsPerUser,
maxCacheBytes: maxCacheBytes,
jobTimeoutSeconds: jobTimeoutSeconds,
evictionGraceSeconds: evictionGraceSeconds,
cacheDirectory: cacheDirectory ?? _validCacheDirectory,
includeCacheDirectory: includeCacheDirectory,
includeFfmpegPath: includeFfmpegPath);
}
}
@@ -0,0 +1,444 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Playback;
using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
/// <summary>
/// Contains unit tests for the <see cref="PlaybackDeliveryHandleService"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class PlaybackDeliveryHandleServiceTests
{
private readonly PlaybackDeliveryHandleService _sut;
private readonly PlaybackDeliveryHandleDtoFixture _playbackDeliveryHandleDtoFixture = new();
private readonly NormalizedTrackRequestDtoFixture _normalizedTrackRequestDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="PlaybackDeliveryHandleServiceTests"/> class.
/// </summary>
public PlaybackDeliveryHandleServiceTests()
{
_sut = new PlaybackDeliveryHandleService();
}
[Fact]
public void IssueDeliveryId_WhenCalled_ShouldReturnA32CharacterLowercaseHexadecimalHandle()
{
// Arrange
PlaybackDeliveryHandleDto delivery = CreateBaseDelivery();
// Act
string handle = _sut.IssueDeliveryId(delivery);
// Assert
Assert.Equal(32, handle.Length);
Assert.Matches("^[0-9a-f]{32}$", handle);
Assert.True(PlaybackDeliveryId.IsValid(handle));
}
[Fact]
public void IssueDeliveryId_WhenDeliveriesDiffer_ShouldReturnDistinctHandles()
{
// Arrange
PlaybackDeliveryHandleDto firstDelivery = CreateBaseDelivery();
PlaybackDeliveryHandleDto secondDelivery = CreateBaseDelivery();
// Act
string firstHandle = _sut.IssueDeliveryId(firstDelivery);
string secondHandle = _sut.IssueDeliveryId(secondDelivery);
// Assert
Assert.NotEqual(firstHandle, secondHandle);
}
[Fact]
public void IssueDeliveryId_WhenTheSameDeliveryIsIssuedAgain_ShouldReturnTheSameHandle()
{
// Arrange
PlaybackDeliveryHandleDto delivery = CreateBaseDelivery();
// Act
string firstHandle = _sut.IssueDeliveryId(delivery);
string secondHandle = _sut.IssueDeliveryId(delivery);
// Assert
Assert.Equal(firstHandle, secondHandle);
}
[Fact]
public void IssueDeliveryId_WhenAnEqualDeliveryIsIssuedAgainAtThePerUserLimit_ShouldReuseTheExistingHandle()
{
// Arrange
PlaybackDeliveryHandleDto delivery = CreateBaseDelivery();
string handle = _sut.IssueDeliveryId(delivery);
// Fill the rest of the per user bound with distinct deliveries, so the next issue would evict this one if it did not reuse it.
for (int index = 0; index < 63; index++)
_sut.IssueDeliveryId(CreateDeliveryFor(delivery.Request.UserId));
PlaybackDeliveryHandleDto equalDelivery = delivery with { Request = delivery.Request with { AllowedRoots = [.. delivery.Request.AllowedRoots] } };
// Act
string reusedHandle = _sut.IssueDeliveryId(equalDelivery);
// Assert
Assert.Equal(handle, reusedHandle);
Result<PlaybackDeliveryHandleDto> result = _sut.GetDelivery(handle, delivery.Request.UserId, delivery.Request.TrackId);
Assert.False(result.IsFailure);
Assert.Same(delivery, result.Value);
}
public static TheoryData<DeliveryVariation> SignatureVariations => new()
{
DeliveryVariation.UserId,
DeliveryVariation.TrackId,
DeliveryVariation.LibraryId,
DeliveryVariation.AlbumId,
DeliveryVariation.ArtistId,
DeliveryVariation.Mode,
DeliveryVariation.Shape,
DeliveryVariation.SourceContainer,
DeliveryVariation.SourceContainerNull,
DeliveryVariation.Container,
DeliveryVariation.Codec,
DeliveryVariation.SegmentDurationSeconds,
DeliveryVariation.DurationInSeconds,
DeliveryVariation.Bitrate,
DeliveryVariation.BitrateNull,
DeliveryVariation.SampleRate,
DeliveryVariation.Channels,
DeliveryVariation.BitDepth,
DeliveryVariation.BitDepthNull,
DeliveryVariation.Quality,
DeliveryVariation.SourcePath,
DeliveryVariation.SourceLength,
DeliveryVariation.SourceLastModifiedUtc,
DeliveryVariation.AllowedRoots
};
[Theory]
[MemberData(nameof(SignatureVariations))]
public void IssueDeliveryId_WhenOneSignatureInputChanges_ShouldReturnADifferentHandle(DeliveryVariation variation)
{
// Arrange
PlaybackDeliveryHandleDto delivery = CreateBaseDelivery();
string handle = _sut.IssueDeliveryId(delivery);
PlaybackDeliveryHandleDto variedDelivery = Vary(delivery, variation);
// Act
string variedHandle = _sut.IssueDeliveryId(variedDelivery);
// Assert
Assert.NotEqual(handle, variedHandle);
}
[Theory]
[InlineData(null)] // an absent handle cannot address a delivery
[InlineData("")] // an empty handle cannot address a delivery
[InlineData(" ")] // a whitespace handle cannot address a delivery
[InlineData("0123456789abcdef0123456789abcdef")] // a well formed handle that was never issued
public void GetDelivery_WhenTheHandleIsMissingOrUnknown_ShouldReturnPlaybackDeliveryNotFoundError(string? deliveryId)
{
// Act
Result<PlaybackDeliveryHandleDto> result = _sut.GetDelivery(deliveryId, Guid.NewGuid(), Guid.NewGuid());
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Playback.PlaybackDeliveryNotFound, result.FirstError);
}
[Fact]
public void GetDelivery_WhenTheHandleWasIssuedToAnotherUser_ShouldReturnPlaybackDeliveryNotFoundError()
{
// Arrange
PlaybackDeliveryHandleDto delivery = CreateBaseDelivery();
string handle = _sut.IssueDeliveryId(delivery);
// Act
Result<PlaybackDeliveryHandleDto> result = _sut.GetDelivery(handle, Guid.NewGuid(), delivery.Request.TrackId);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Playback.PlaybackDeliveryNotFound, result.FirstError);
}
[Fact]
public void GetDelivery_WhenTheHandleDescribesAnotherTrack_ShouldReturnPlaybackDeliveryNotFoundError()
{
// Arrange
PlaybackDeliveryHandleDto delivery = CreateBaseDelivery();
string handle = _sut.IssueDeliveryId(delivery);
// Act
Result<PlaybackDeliveryHandleDto> result = _sut.GetDelivery(handle, delivery.Request.UserId, Guid.NewGuid());
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Playback.PlaybackDeliveryNotFound, result.FirstError);
}
[Fact]
public void GetDelivery_WhenTheHandleWasIssuedToTheUserForTheTrack_ShouldReturnTheIssuedDelivery()
{
// Arrange
PlaybackDeliveryHandleDto delivery = CreateBaseDelivery();
string handle = _sut.IssueDeliveryId(delivery);
// Act
Result<PlaybackDeliveryHandleDto> result = _sut.GetDelivery(handle, delivery.Request.UserId, delivery.Request.TrackId);
// Assert
Assert.False(result.IsFailure);
Assert.Same(delivery, result.Value);
Assert.Equal(delivery.Request.TrackId, result.Value.Request.TrackId);
Assert.Equal(delivery.Request.UserId, result.Value.Request.UserId);
Assert.Equal(delivery.Shape, result.Value.Shape);
Assert.Equal(delivery.LibraryId, result.Value.LibraryId);
Assert.Equal(delivery.AlbumId, result.Value.AlbumId);
Assert.Equal(delivery.ArtistId, result.Value.ArtistId);
}
[Fact]
public void IssueDeliveryId_WhenAUserExceedsThePerUserLimit_ShouldEvictOnlyTheOldestHandleOfThatUser()
{
// Arrange
Guid userId = Guid.NewGuid();
Guid otherUserId = Guid.NewGuid();
PlaybackDeliveryHandleDto otherUserDelivery = CreateDeliveryFor(otherUserId);
string otherUserHandle = _sut.IssueDeliveryId(otherUserDelivery);
List<(string Handle, Guid TrackId)> handles = [];
for (int index = 0; index < 64; index++)
{
PlaybackDeliveryHandleDto delivery = CreateDeliveryFor(userId);
handles.Add((_sut.IssueDeliveryId(delivery), delivery.Request.TrackId));
}
// Act
PlaybackDeliveryHandleDto newestDelivery = CreateDeliveryFor(userId);
string newestHandle = _sut.IssueDeliveryId(newestDelivery);
// Assert
Assert.True(_sut.GetDelivery(handles[0].Handle, userId, handles[0].TrackId).IsFailure);
for (int index = 1; index < handles.Count; index++)
Assert.True(_sut.GetDelivery(handles[index].Handle, userId, handles[index].TrackId).IsSuccess);
Assert.True(_sut.GetDelivery(newestHandle, userId, newestDelivery.Request.TrackId).IsSuccess);
Assert.True(_sut.GetDelivery(otherUserHandle, otherUserId, otherUserDelivery.Request.TrackId).IsSuccess);
}
[Fact]
public void IssueDeliveryId_WhenTheGlobalLimitIsExceeded_ShouldEvictOnlyTheOldestHandle()
{
// Arrange
PlaybackDeliveryHandleService sut = new();
Guid[] users = [.. Enumerable.Range(0, 400).Select(_ => Guid.NewGuid())];
string? oldestHandle = null;
Guid oldestUserId = Guid.Empty;
Guid oldestTrackId = Guid.Empty;
string? secondOldestHandle = null;
Guid secondOldestUserId = Guid.Empty;
Guid secondOldestTrackId = Guid.Empty;
string? newestHandle = null;
Guid newestUserId = Guid.Empty;
Guid newestTrackId = Guid.Empty;
for (int index = 0; index < 20_000; index++)
{
// The per user bound is 64, so each user is given exactly 64 deliveries and never triggers a per user eviction.
Guid userId = users[index / 64];
PlaybackDeliveryHandleDto delivery = CreateDeliveryFor(userId);
string handle = sut.IssueDeliveryId(delivery);
if (index == 0)
{
oldestHandle = handle;
oldestUserId = userId;
oldestTrackId = delivery.Request.TrackId;
}
else if (index == 1)
{
secondOldestHandle = handle;
secondOldestUserId = userId;
secondOldestTrackId = delivery.Request.TrackId;
}
if (index == 19_999)
{
newestHandle = handle;
newestUserId = userId;
newestTrackId = delivery.Request.TrackId;
}
}
PlaybackDeliveryHandleDto extraDelivery = CreateDeliveryFor(Guid.NewGuid());
// Act
string extraHandle = sut.IssueDeliveryId(extraDelivery);
// Assert
Assert.True(sut.GetDelivery(oldestHandle, oldestUserId, oldestTrackId).IsFailure);
Assert.True(sut.GetDelivery(secondOldestHandle, secondOldestUserId, secondOldestTrackId).IsSuccess);
Assert.True(sut.GetDelivery(newestHandle, newestUserId, newestTrackId).IsSuccess);
Assert.True(sut.GetDelivery(extraHandle, extraDelivery.Request.UserId, extraDelivery.Request.TrackId).IsSuccess);
}
[Fact]
public async Task IssueDeliveryId_WhenTheSameDeliveryIsIssuedConcurrently_ShouldReturnOneIdenticalHandle()
{
// Arrange
PlaybackDeliveryHandleDto delivery = CreateBaseDelivery();
// Act
string[] handles = await Task.WhenAll(Enumerable.Range(0, 32).Select(_ => Task.Run(() => _sut.IssueDeliveryId(delivery))));
// Assert
Assert.Single(handles.Distinct());
Assert.True(_sut.GetDelivery(handles[0], delivery.Request.UserId, delivery.Request.TrackId).IsSuccess);
}
[Fact]
public async Task IssueDeliveryId_WhenDifferentDeliveriesAreIssuedConcurrently_ShouldMakeEveryHandleResolvable()
{
// Arrange
PlaybackDeliveryHandleDto[] deliveries = [.. Enumerable.Range(0, 32).Select(_ => CreateDeliveryFor(Guid.NewGuid()))];
// Act
string[] handles = await Task.WhenAll(deliveries.Select(delivery => Task.Run(() => _sut.IssueDeliveryId(delivery))));
// Assert
Assert.Equal(deliveries.Length, handles.Distinct().Count());
for (int index = 0; index < deliveries.Length; index++)
Assert.True(_sut.GetDelivery(handles[index], deliveries[index].Request.UserId, deliveries[index].Request.TrackId).IsSuccess);
}
/// <summary>
/// The single input of the delivery signature that a variation changes.
/// </summary>
public enum DeliveryVariation
{
UserId,
TrackId,
LibraryId,
AlbumId,
ArtistId,
Mode,
Shape,
SourceContainer,
SourceContainerNull,
Container,
Codec,
SegmentDurationSeconds,
DurationInSeconds,
Bitrate,
BitrateNull,
SampleRate,
Channels,
BitDepth,
BitDepthNull,
Quality,
SourcePath,
SourceLength,
SourceLastModifiedUtc,
AllowedRoots
}
/// <summary>
/// Creates a delivery with every signature input explicitly pinned.
/// </summary>
/// <returns>The created delivery.</returns>
private PlaybackDeliveryHandleDto CreateBaseDelivery()
{
return _playbackDeliveryHandleDtoFixture.Create(
request: CreateRequest(userId: Guid.NewGuid(), trackId: Guid.NewGuid()),
shape: PlaybackDeliveryShape.TimeAddressedSegments,
libraryId: Guid.Parse("11111111-1111-1111-1111-111111111111"),
albumId: Guid.Parse("22222222-2222-2222-2222-222222222222"),
artistId: Guid.Parse("33333333-3333-3333-3333-333333333333"));
}
/// <summary>
/// Creates a delivery for a user whose track is unique to the delivery.
/// </summary>
/// <param name="userId">The Id of the user the delivery is issued to.</param>
/// <returns>The created delivery.</returns>
private PlaybackDeliveryHandleDto CreateDeliveryFor(Guid userId)
{
return _playbackDeliveryHandleDtoFixture.Create(
request: CreateRequest(userId: userId, trackId: Guid.NewGuid()),
shape: PlaybackDeliveryShape.TimeAddressedSegments,
libraryId: Guid.NewGuid(),
albumId: Guid.NewGuid(),
artistId: Guid.NewGuid());
}
/// <summary>
/// Changes exactly one input of the delivery signature.
/// </summary>
/// <param name="delivery">The delivery to vary.</param>
/// <param name="variation">The input to change.</param>
/// <returns>The varied delivery.</returns>
private static PlaybackDeliveryHandleDto Vary(PlaybackDeliveryHandleDto delivery, DeliveryVariation variation)
{
return variation switch
{
DeliveryVariation.UserId => delivery with { Request = delivery.Request with { UserId = Guid.NewGuid() } },
DeliveryVariation.TrackId => delivery with { Request = delivery.Request with { TrackId = Guid.NewGuid() } },
DeliveryVariation.LibraryId => delivery with { LibraryId = Guid.NewGuid() },
DeliveryVariation.AlbumId => delivery with { AlbumId = Guid.NewGuid() },
DeliveryVariation.ArtistId => delivery with { ArtistId = Guid.NewGuid() },
DeliveryVariation.Mode => delivery with { Request = delivery.Request with { Mode = PlaybackDeliveryMode.Remux } },
DeliveryVariation.Shape => delivery with { Shape = PlaybackDeliveryShape.ByteRangeSeekable },
DeliveryVariation.SourceContainer => delivery with { Request = delivery.Request with { SourceContainer = "WAV" } },
DeliveryVariation.SourceContainerNull => delivery with { Request = delivery.Request with { SourceContainer = null } },
DeliveryVariation.Container => delivery with { Request = delivery.Request with { Container = "AAC" } },
DeliveryVariation.Codec => delivery with { Request = delivery.Request with { Codec = "AAC" } },
DeliveryVariation.SegmentDurationSeconds => delivery with { Request = delivery.Request with { SegmentDurationSeconds = 10 } },
DeliveryVariation.DurationInSeconds => delivery with { Request = delivery.Request with { DurationInSeconds = 300 } },
DeliveryVariation.Bitrate => delivery with { Request = delivery.Request with { Bitrate = 320 } },
DeliveryVariation.BitrateNull => delivery with { Request = delivery.Request with { Bitrate = null } },
DeliveryVariation.SampleRate => delivery with { Request = delivery.Request with { SampleRate = 96000 } },
DeliveryVariation.Channels => delivery with { Request = delivery.Request with { Channels = 6 } },
DeliveryVariation.BitDepth => delivery with { Request = delivery.Request with { BitDepth = 16 } },
DeliveryVariation.BitDepthNull => delivery with { Request = delivery.Request with { BitDepth = null } },
DeliveryVariation.Quality => delivery with { Request = delivery.Request with { Quality = PlaybackStreamingQuality.Low } },
DeliveryVariation.SourcePath => delivery with { Request = delivery.Request with { SourcePath = "/music/incoming/other.flac" } },
DeliveryVariation.SourceLength => delivery with { Request = delivery.Request with { SourceLength = 999 } },
DeliveryVariation.SourceLastModifiedUtc => delivery with { Request = delivery.Request with { SourceLastModifiedUtc = new DateTime(2026, 2, 3, 4, 5, 6, DateTimeKind.Utc) } },
DeliveryVariation.AllowedRoots => delivery with { Request = delivery.Request with { AllowedRoots = [.. delivery.Request.AllowedRoots.Take(1), "/music/other"] } },
_ => throw new ArgumentOutOfRangeException(nameof(variation), variation, "Unsupported delivery variation.")
};
}
/// <summary>
/// Creates a normalization request with every signature input explicitly pinned.
/// </summary>
/// <param name="userId">The Id of the user the delivery is issued to.</param>
/// <param name="trackId">The Id of the track the delivery describes.</param>
/// <returns>The created request.</returns>
private NormalizedTrackRequestDto CreateRequest(Guid userId, Guid trackId)
{
return _normalizedTrackRequestDtoFixture.Create(
trackId: trackId,
userId: userId,
sourcePath: "/music/library/track.flac",
allowedRoots: ["/music/library", "/music/incoming"],
sourceContainer: "FLAC",
mode: PlaybackDeliveryMode.Transcode,
container: "MP3",
codec: "MP3",
segmentDurationSeconds: 6,
durationInSeconds: 245,
bitrate: 900,
sampleRate: 48000,
channels: 2,
bitDepth: 24,
quality: PlaybackStreamingQuality.High,
sourceLength: 123456,
sourceLastModifiedUtc: new DateTime(2026, 1, 2, 3, 4, 5, DateTimeKind.Utc));
}
}
@@ -0,0 +1,207 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Path;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform;
using Lumina.Domain.SharedKernel.Common.Enums.Playback;
using Lumina.Infrastructure.Common.Models.DTO.Configuration;
using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using Lumina.Infrastructure.Fixtures.Common.Models.DTO.Configuration;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.IO.Abstractions;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
/// <summary>
/// Contains unit tests for the <see cref="TrackNormalizationService"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class TrackNormalizationServiceTests : IDisposable
{
private readonly TrackNormalizationService _sut;
private readonly NormalizedTrackRequestDtoFixture _normalizedTrackRequestDtoFixture = new();
private readonly TranscodingSettingsDtoFixture _transcodingSettingsDtoFixture = new();
private readonly string _sandboxRoot;
private readonly string _cacheDirectory;
private readonly string _sourceRoot;
private readonly string _sourcePath;
private readonly long _sourceLength;
private readonly DateTime _sourceLastModifiedUtc;
/// <summary>
/// Initializes a new instance of the <see cref="TrackNormalizationServiceTests"/> class.
/// </summary>
public TrackNormalizationServiceTests()
{
_sandboxRoot = Path.Combine(Path.GetTempPath(), "lumina-track-normalization-tests-" + Guid.NewGuid().ToString("N"));
_cacheDirectory = Path.Combine(_sandboxRoot, "cache");
_sourceRoot = Path.Combine(_sandboxRoot, "source");
_sourcePath = Path.Combine(_sourceRoot, "track.flac");
Directory.CreateDirectory(_cacheDirectory);
Directory.CreateDirectory(_sourceRoot);
File.WriteAllBytes(_sourcePath, new byte[512]);
_sourceLength = new FileInfo(_sourcePath).Length;
_sourceLastModifiedUtc = File.GetLastWriteTimeUtc(_sourcePath);
// The real path service is used, with the real path strategy of the current platform, so containment follows the file system rules of the host.
IPlatformContext platformContext = Substitute.For<IPlatformContext>();
IPathStrategy pathStrategy = OperatingSystem.IsWindows()
? new WindowsPathStrategy(new FileSystem())
: new UnixPathStrategy(new FileSystem());
platformContext.PathStrategy.Returns(pathStrategy);
IPlatformContextManager platformContextManager = Substitute.For<IPlatformContextManager>();
platformContextManager.GetCurrentContext().Returns(platformContext);
IPathService pathService = new PathService(platformContextManager);
TranscodingSettingsDto settings = _transcodingSettingsDtoFixture.Create(
ffmpegPath: Path.Combine(_sandboxRoot, "missing-ffmpeg"),
maxConcurrentJobs: 2,
maxConcurrentJobsPerUser: 1,
maxCacheBytes: 100 * 1024 * 1024,
jobTimeoutSeconds: 60,
evictionGraceSeconds: 10,
cacheDirectory: _cacheDirectory);
TranscodingToolchainStatus toolchainStatus = new();
_sut = new TrackNormalizationService(Options.Create(settings), NullLogger<TrackNormalizationService>.Instance, pathService, toolchainStatus);
}
[Fact]
public async Task GetOrCreateNormalizedTrackAsync_WhenTheUserIdIsEmpty_ShouldReturnNormalizationFailedError()
{
// Arrange
NormalizedTrackRequestDto request = CreateRequest(userId: Guid.Empty);
// Act
Result<NormalizedTrackDto> result = await _sut.GetOrCreateNormalizedTrackAsync(request, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Playback.NormalizationFailed, result.FirstError);
}
[Theory]
[InlineData(true)] // the source file length no longer matches the declared delivery
[InlineData(false)] // the source file modification time no longer matches the declared delivery
public async Task GetOrCreateNormalizedTrackAsync_WhenTheSourceFileChangedSinceTheDeliveryWasDeclared_ShouldReturnPlaybackDeliveryChangedError(bool isLengthChanged)
{
// Arrange
NormalizedTrackRequestDto request = CreateRequest(
sourceLength: isLengthChanged ? _sourceLength + 1 : _sourceLength,
sourceLastModifiedUtc: isLengthChanged ? _sourceLastModifiedUtc : _sourceLastModifiedUtc.AddMinutes(-1));
// Act
Result<NormalizedTrackDto> result = await _sut.GetOrCreateNormalizedTrackAsync(request, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Playback.PlaybackDeliveryChanged, result.FirstError);
}
[Fact(Skip = "Production bug: a missing source file inside an allowed root throws FileNotFoundException from HasReparsePointBelow (File.GetAttributes on the leaf) instead of returning Errors.Music.TrackFileNotFound. The exception escapes GetOrCreateNormalizedTrackAsync, so the contract of the method is violated for a track deleted between the manifest and the first segment request.")]
public async Task GetOrCreateNormalizedTrackAsync_WhenTheSourceFileDoesNotExist_ShouldReturnTrackFileNotFoundError()
{
// Arrange
NormalizedTrackRequestDto request = CreateRequest(sourcePath: Path.Combine(_sourceRoot, "missing.flac"));
// Act
Result<NormalizedTrackDto> result = await _sut.GetOrCreateNormalizedTrackAsync(request, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.TrackFileNotFound, result.FirstError);
}
[Fact]
public async Task GetOrCreateNormalizedTrackAsync_WhenTheSourcePathIsOutsideEveryAllowedRoot_ShouldReturnTrackFileNotFoundError()
{
// Arrange
NormalizedTrackRequestDto request = CreateRequest(allowedRoots: [Path.Combine(_sandboxRoot, "other")]);
// Act
Result<NormalizedTrackDto> result = await _sut.GetOrCreateNormalizedTrackAsync(request, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.TrackFileNotFound, result.FirstError);
}
[Fact]
public async Task GetOrCreateNormalizedTrackAsync_WhenTheServiceIsDisposed_ShouldReturnNormalizationUnavailableError()
{
// Arrange
NormalizedTrackRequestDto request = CreateRequest();
_sut.Dispose();
// Act
Result<NormalizedTrackDto> result = await _sut.GetOrCreateNormalizedTrackAsync(request, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Playback.NormalizationUnavailable, result.FirstError);
}
/// <summary>
/// Releases the service and the temporary directories of the test.
/// </summary>
public void Dispose()
{
_sut.Dispose();
try
{
if (Directory.Exists(_sandboxRoot))
Directory.Delete(_sandboxRoot, recursive: true);
}
catch (IOException)
{
// A temporary directory that cannot be removed does not fail the test.
}
}
/// <summary>
/// Creates a normalization request that matches the source file of the test.
/// </summary>
/// <param name="userId">The Id of the user whose request starts the production.</param>
/// <param name="sourcePath">The file system path of the stored audio file of the track.</param>
/// <param name="allowedRoots">The content locations the source path is allowed to be inside.</param>
/// <param name="sourceLength">The length the source file had when the delivery was declared, in bytes.</param>
/// <param name="sourceLastModifiedUtc">The last modification time the source file had when the delivery was declared.</param>
/// <returns>The created request.</returns>
private NormalizedTrackRequestDto CreateRequest(
Guid? userId = null,
string? sourcePath = null,
IReadOnlyList<string>? allowedRoots = null,
long? sourceLength = null,
DateTime? sourceLastModifiedUtc = null)
{
return _normalizedTrackRequestDtoFixture.Create(
trackId: Guid.NewGuid(),
userId: userId ?? Guid.NewGuid(),
sourcePath: sourcePath ?? _sourcePath,
allowedRoots: allowedRoots ?? [_sourceRoot],
sourceContainer: "FLAC",
mode: PlaybackDeliveryMode.Transcode,
container: "MP3",
codec: "MP3",
segmentDurationSeconds: 6,
durationInSeconds: 120,
bitrate: 900,
sampleRate: 44100,
channels: 2,
bitDepth: 16,
quality: PlaybackStreamingQuality.Auto,
sourceLength: sourceLength ?? _sourceLength,
sourceLastModifiedUtc: sourceLastModifiedUtc ?? _sourceLastModifiedUtc);
}
}
@@ -47,4 +47,64 @@ public class MusicMimeTypesTests
// Assert
Assert.Equal("application/octet-stream", result);
}
[Theory]
[InlineData("MP3", "audio/mpeg")] // mp3 container
[InlineData("FLAC", "audio/flac")] // flac container
[InlineData("MP4", "audio/mp4")] // mp4 container
[InlineData("M4A", "audio/mp4")] // m4a container
[InlineData("AAC", "audio/aac")] // aac container
[InlineData("OGG", "audio/ogg")] // ogg container
[InlineData("OPUS", "audio/ogg")] // opus container
[InlineData("WAV", "audio/wav")] // wav container
public void GetContainerMimeType_WhenContainerIsMapped_ShouldReturnMappedMimeType(string container, string expectedMimeType)
{
// Act
string result = MusicMimeTypes.GetContainerMimeType(container);
// Assert
Assert.Equal(expectedMimeType, result);
}
[Theory]
[InlineData("mp3", "audio/mpeg")] // lowercase mp3 container
[InlineData("Flac", "audio/flac")] // mixed case flac container
[InlineData("mP4", "audio/mp4")] // mixed case mp4 container
[InlineData("opus", "audio/ogg")] // lowercase opus container
public void GetContainerMimeType_WhenContainerDiffersInCase_ShouldReturnMappedMimeType(string container, string expectedMimeType)
{
// Act
string result = MusicMimeTypes.GetContainerMimeType(container);
// Assert
Assert.Equal(expectedMimeType, result);
}
[Theory]
[InlineData(" MP3 ", "audio/mpeg")] // leading and trailing whitespace around mp3
[InlineData("\tOGG", "audio/ogg")] // leading tab around ogg
[InlineData("WAV\n", "audio/wav")] // trailing newline around wav
public void GetContainerMimeType_WhenContainerHasSurroundingWhitespace_ShouldReturnMappedMimeType(string container, string expectedMimeType)
{
// Act
string result = MusicMimeTypes.GetContainerMimeType(container);
// Assert
Assert.Equal(expectedMimeType, result);
}
[Theory]
[InlineData(null)] // an absent container has no mime mapping
[InlineData("")] // an empty container has no mime mapping
[InlineData(" ")] // a whitespace only container has no mime mapping
[InlineData("WMA")] // a known file format that is not a mapped delivery container
[InlineData("not-a-container")] // an unknown container has no mime mapping
public void GetContainerMimeType_WhenContainerIsUnknown_ShouldReturnOpaqueBinaryMimeType(string? container)
{
// Act
string result = MusicMimeTypes.GetContainerMimeType(container);
// Assert
Assert.Equal("application/octet-stream", result);
}
}
@@ -206,6 +206,25 @@ public class BaseEndpointTests
Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode);
}
[Fact]
public void Problem_WhenCalledWithResourceUnavailableError_ShouldReturnServiceUnavailableStatusCode()
{
// Arrange
List<Error> errors = [Error.ResourceUnavailable("ErrorCode", "ErrorDescription")];
// Act
IResult result = _sut.TestProblem(errors);
// Assert
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status503ServiceUnavailable, problemResult.StatusCode);
Assert.Equal(StatusCodes.Status503ServiceUnavailable, problemResult.ProblemDetails.Status);
Assert.Equal("ErrorCode", problemResult.ProblemDetails.Title);
Assert.Equal("ErrorDescription", problemResult.ProblemDetails.Detail);
Assert.NotNull(problemResult.ProblemDetails.Instance);
Assert.Contains("traceId", problemResult.ProblemDetails.Extensions.Keys);
}
[Fact]
public void Problem_WhenCalledWithMixedErrorsStartingWithValidation_ShouldReturnTheValidationStatusCode()
{
@@ -0,0 +1,222 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Microsoft.AspNetCore.Http;
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Common;
/// <summary>
/// Contains unit tests for the <see cref="DisposingStreamResult"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DisposingStreamResultTests
{
/// <summary>
/// Initializes a new instance of the <see cref="DisposingStreamResultTests"/> class.
/// </summary>
public DisposingStreamResultTests()
{
}
[Fact]
public async Task ExecuteAsync_WhenContentIsProvided_ShouldWriteEveryByteToResponseBody()
{
// Arrange
byte[] expectedBytes = CreateBytes(512);
using MemoryStream content = new(expectedBytes);
DisposingStreamResult sut = new(content, "audio/mpeg", expectedBytes.Length);
DefaultHttpContext httpContext = CreateHttpContext();
// Act
await sut.ExecuteAsync(httpContext);
// Assert
httpContext.Response.Body.Position = 0;
using MemoryStream writtenBody = new();
await httpContext.Response.Body.CopyToAsync(writtenBody);
Assert.Equal(expectedBytes, writtenBody.ToArray());
}
[Fact]
public async Task ExecuteAsync_WhenContentLengthIsProvided_ShouldSetContentTypeAndContentLength()
{
// Arrange
byte[] contentBytes = CreateBytes(128);
using MemoryStream content = new(contentBytes);
DisposingStreamResult sut = new(content, "audio/mp4", contentBytes.Length);
DefaultHttpContext httpContext = CreateHttpContext();
// Act
await sut.ExecuteAsync(httpContext);
// Assert
Assert.Equal("audio/mp4", httpContext.Response.ContentType);
Assert.Equal(contentBytes.Length, httpContext.Response.ContentLength);
}
[Fact]
public async Task ExecuteAsync_WhenContentLengthIsNull_ShouldLeaveResponseContentLengthUnset()
{
// Arrange
byte[] contentBytes = CreateBytes(64);
using MemoryStream content = new(contentBytes);
DisposingStreamResult sut = new(content, "audio/ogg", null);
DefaultHttpContext httpContext = CreateHttpContext();
// Act
await sut.ExecuteAsync(httpContext);
// Assert
Assert.Equal("audio/ogg", httpContext.Response.ContentType);
Assert.Null(httpContext.Response.ContentLength);
}
[Fact]
public async Task ExecuteAsync_WhenWriteCompletes_ShouldDisposeTheContentStream()
{
// Arrange
byte[] contentBytes = CreateBytes(32);
DisposalTrackingStream content = new(contentBytes);
DisposingStreamResult sut = new(content, "audio/mpeg", contentBytes.Length);
DefaultHttpContext httpContext = CreateHttpContext();
// Act
await sut.ExecuteAsync(httpContext);
// Assert
Assert.True(content.IsDisposed);
}
[Fact]
public async Task ExecuteAsync_WhenCopyToAsyncThrows_ShouldDisposeTheContentStreamAndPropagateTheException()
{
// Arrange
ThrowingCopyStream content = new(CreateBytes(32));
DisposingStreamResult sut = new(content, "audio/mpeg", null);
DefaultHttpContext httpContext = CreateHttpContext();
// Act
Task operationTask = sut.ExecuteAsync(httpContext);
// Assert
await Assert.ThrowsAsync<IOException>(() => operationTask);
Assert.True(content.IsDisposed);
}
[Fact]
public async Task ExecuteAsync_WhenStreamWasPartiallyRead_ShouldCopyFromTheCurrentPosition()
{
// Arrange
byte[] contentBytes = CreateBytes(100);
using MemoryStream content = new(contentBytes);
content.Position = 37;
DisposingStreamResult sut = new(content, "audio/wav", contentBytes.Length - 37);
DefaultHttpContext httpContext = CreateHttpContext();
// Act
await sut.ExecuteAsync(httpContext);
// Assert
httpContext.Response.Body.Position = 0;
using MemoryStream writtenBody = new();
await httpContext.Response.Body.CopyToAsync(writtenBody);
Assert.Equal(contentBytes[37..], writtenBody.ToArray());
}
/// <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 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))];
}
/// <summary>
/// A memory stream that records whether it was disposed.
/// </summary>
private sealed class DisposalTrackingStream : MemoryStream
{
/// <summary>
/// Gets whether the stream was disposed.
/// </summary>
public bool IsDisposed { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="DisposalTrackingStream"/> class.
/// </summary>
/// <param name="content">The bytes of the stream.</param>
public DisposalTrackingStream(byte[] content) : base(content)
{
}
/// <summary>
/// Releases the resources of the stream and records the disposal.
/// </summary>
/// <param name="disposing">Whether managed resources are being disposed.</param>
protected override void Dispose(bool disposing)
{
IsDisposed = true;
base.Dispose(disposing);
}
}
/// <summary>
/// A memory stream whose copy operation always fails.
/// </summary>
private sealed class ThrowingCopyStream : MemoryStream
{
/// <summary>
/// Gets whether the stream was disposed.
/// </summary>
public bool IsDisposed { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="ThrowingCopyStream"/> class.
/// </summary>
/// <param name="content">The bytes of the stream.</param>
public ThrowingCopyStream(byte[] content) : base(content)
{
}
/// <summary>
/// Simulates a failed write to the destination stream.
/// </summary>
/// <param name="destination">The destination stream.</param>
/// <param name="bufferSize">The size of the buffer used by the copy.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>This method never returns, it always throws.</returns>
public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)
{
throw new IOException("The destination stream rejected the content.");
}
/// <summary>
/// Releases the resources of the stream and records the disposal.
/// </summary>
/// <param name="disposing">Whether managed resources are being disposed.</param>
protected override void Dispose(bool disposing)
{
IsDisposed = true;
base.Dispose(disposing);
}
}
}
@@ -0,0 +1,197 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetPlaybackManifest;
using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetPlaybackManifest;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetPlaybackManifest;
/// <summary>
/// Contains unit tests for the <see cref="GetPlaybackManifestEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetPlaybackManifestEndpointTests
{
private readonly IQueryHandler<GetPlaybackManifestQuery, Result<PlaybackManifestResponse>> _mockHandler;
private readonly GetPlaybackManifestEndpoint _sut;
private readonly PlaybackManifestResponseFixture _playbackManifestResponseFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetPlaybackManifestEndpointTests"/> class.
/// </summary>
public GetPlaybackManifestEndpointTests()
{
_mockHandler = Substitute.For<IQueryHandler<GetPlaybackManifestQuery, Result<PlaybackManifestResponse>>>();
_sut = Factory.Create<GetPlaybackManifestEndpoint>(_mockHandler);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithTheManifest()
{
// Arrange
PlaybackManifestResponse expectedResponse = _playbackManifestResponseFixture.Create();
_mockHandler.HandleAsync(Arg.Any<GetPlaybackManifestQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(expectedResponse));
SetRouteValues();
// Act
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
Ok<PlaybackManifestResponse> okResult = Assert.IsType<Ok<PlaybackManifestResponse>>(result);
Assert.Equal(expectedResponse, okResult.Value);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldSetPrivateNoStoreCacheHeaders()
{
// Arrange
_mockHandler.HandleAsync(Arg.Any<GetPlaybackManifestQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_playbackManifestResponseFixture.Create()));
SetRouteValues();
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString());
Assert.Equal("Authorization", _sut.HttpContext.Response.Headers["Vary"].ToString());
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
{
// Arrange
Error expectedError = DomainErrors.Music.TrackNotFound;
_mockHandler.HandleAsync(Arg.Any<GetPlaybackManifestQuery>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
SetRouteValues();
// Act
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status404NotFound, problemResult.StatusCode);
Assert.Equal(StatusCodes.Status404NotFound, problemResult.ProblemDetails.Status);
Assert.Equal(expectedError.Code, problemResult.ProblemDetails.Title);
Assert.Equal(expectedError.Description, problemResult.ProblemDetails.Detail);
Assert.Contains("traceId", problemResult.ProblemDetails.Extensions.Keys);
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldSendTheRouteValuesAndTheStreamPathsToTheHandler()
{
// Arrange
string libraryId = "11111111-1111-1111-1111-111111111111";
string artistId = "22222222-2222-2222-2222-222222222222";
string albumId = "33333333-3333-3333-3333-333333333333";
string trackId = "44444444-4444-4444-4444-444444444444";
_mockHandler.HandleAsync(Arg.Any<GetPlaybackManifestQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_playbackManifestResponseFixture.Create()));
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId;
_sut.HttpContext.Request.RouteValues["artistId"] = artistId;
_sut.HttpContext.Request.RouteValues["albumId"] = albumId;
_sut.HttpContext.Request.RouteValues["trackId"] = trackId;
_sut.HttpContext.Request.QueryString = new QueryString("?capabilities=mp3/mp3");
string expectedStreamPath = ApiRoutes.Tracks.STREAM_TRACK
.Replace("{libraryId}", libraryId)
.Replace("{artistId}", artistId)
.Replace("{albumId}", albumId)
.Replace("{trackId}", trackId);
string expectedSegmentStreamPathTemplate = ApiRoutes.Tracks.STREAM_TRACK_SEGMENT
.Replace("{libraryId}", libraryId)
.Replace("{artistId}", artistId)
.Replace("{albumId}", albumId)
.Replace("{trackId}", trackId);
CancellationToken cancellationToken = CancellationToken.None;
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<GetPlaybackManifestQuery>(query =>
query.LibraryId == libraryId &&
query.ArtistId == artistId &&
query.AlbumId == albumId &&
query.TrackId == trackId &&
query.Capabilities == "mp3/mp3" &&
query.StreamPath == expectedStreamPath &&
query.SegmentStreamPathTemplate == expectedSegmentStreamPathTemplate &&
query.SegmentStreamPathTemplate.Contains("{deliveryId}") &&
query.SegmentStreamPathTemplate.Contains("{segmentIndex}")),
Arg.Is(cancellationToken));
Assert.DoesNotContain("http", expectedStreamPath, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("http", expectedSegmentStreamPathTemplate, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task ExecuteAsync_WhenCapabilitiesAreAbsent_ShouldSendAnEmptyCapabilitiesValueToTheHandler()
{
// Arrange
_mockHandler.HandleAsync(Arg.Any<GetPlaybackManifestQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_playbackManifestResponseFixture.Create()));
SetRouteValues();
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<GetPlaybackManifestQuery>(query => query.Capabilities == string.Empty),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
CancellationTokenSource cancellationTokenSource = new();
TaskCompletionSource<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
_mockHandler.HandleAsync(Arg.Any<GetPlaybackManifestQuery>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Task.Run(async () =>
{
operationStarted.SetResult(true);
await cancellationRequested.Task;
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From(_playbackManifestResponseFixture.Create());
}, callInfo.Arg<CancellationToken>()));
SetRouteValues();
// Act
Task<IResult> operationTask = _sut.ExecuteAsync(EmptyRequest.Instance, cancellationTokenSource.Token);
await operationStarted.Task;
cancellationTokenSource.Cancel();
cancellationRequested.SetResult(true);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
}
/// <summary>
/// Sets the four route values the endpoint reads from the route.
/// </summary>
private void SetRouteValues()
{
_sut.HttpContext.Request.RouteValues["libraryId"] = Guid.NewGuid().ToString();
_sut.HttpContext.Request.RouteValues["artistId"] = Guid.NewGuid().ToString();
_sut.HttpContext.Request.RouteValues["albumId"] = Guid.NewGuid().ToString();
_sut.HttpContext.Request.RouteValues["trackId"] = Guid.NewGuid().ToString();
}
}
@@ -0,0 +1,286 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrackSegment;
using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetTrackSegment;
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.Threading;
using System.Threading.Tasks;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetTrackSegment;
/// <summary>
/// Contains unit tests for the <see cref="GetTrackSegmentEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetTrackSegmentEndpointTests
{
private readonly IQueryHandler<GetTrackSegmentQuery, Result<NormalizedTrackSegmentDataDto>> _mockHandler;
private readonly GetTrackSegmentEndpoint _sut;
private readonly NormalizedTrackSegmentDataDtoFixture _normalizedTrackSegmentDataDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetTrackSegmentEndpointTests"/> class.
/// </summary>
public GetTrackSegmentEndpointTests()
{
_mockHandler = Substitute.For<IQueryHandler<GetTrackSegmentQuery, Result<NormalizedTrackSegmentDataDto>>>();
_sut = Factory.Create<GetTrackSegmentEndpoint>(_mockHandler);
}
[Theory]
[InlineData("MP4", "audio/mp4")] // mp4 delivery container
[InlineData("OGG", "audio/ogg")] // ogg delivery container
[InlineData("MP3", "audio/mpeg")] // mp3 delivery container
[InlineData("not-a-container", "application/octet-stream")] // an unknown delivery container falls back to opaque binary
public async Task ExecuteAsync_WhenSegmentIsProduced_ShouldReturnDisposingStreamResultWithTheSegment(string container, string expectedContentType)
{
// Arrange
byte[] segmentBytes = CreateBytes(256);
MemoryStream segmentContent = new(segmentBytes);
NormalizedTrackSegmentDataDto segment = _normalizedTrackSegmentDataDtoFixture.Create(
content: segmentContent,
length: segmentBytes.Length,
startSeconds: 6.5m,
container: container,
segmentCount: 12,
durationInSeconds: 300);
_mockHandler.HandleAsync(Arg.Any<GetTrackSegmentQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(segment));
SetRouteValues();
// Act
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
DisposingStreamResult streamResult = Assert.IsType<DisposingStreamResult>(result);
Assert.Equal("nosniff", _sut.HttpContext.Response.Headers["X-Content-Type-Options"].ToString());
Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString());
Assert.Equal("Authorization", _sut.HttpContext.Response.Headers["Vary"].ToString());
Assert.Equal("12", _sut.HttpContext.Response.Headers["X-Lumina-Segment-Count"].ToString());
Assert.Equal("6.5", _sut.HttpContext.Response.Headers["X-Segment-Start-Seconds"].ToString());
Assert.Equal("300", _sut.HttpContext.Response.Headers["X-Lumina-Track-Duration-Seconds"].ToString());
_sut.HttpContext.Response.Body = new MemoryStream();
await streamResult.ExecuteAsync(_sut.HttpContext);
Assert.Equal(expectedContentType, _sut.HttpContext.Response.ContentType);
Assert.Equal(segmentBytes.Length, _sut.HttpContext.Response.ContentLength);
Assert.Equal(segmentBytes, ReadResponseBody(_sut.HttpContext));
Assert.Throws<ObjectDisposedException>(() => segmentContent.ReadByte());
}
[Fact]
public async Task ExecuteAsync_WhenCurrentCultureUsesACommaDecimalSeparator_ShouldWriteTheSegmentStartInvariantly()
{
// Arrange
CultureInfo previousCulture = CultureInfo.CurrentCulture;
MemoryStream segmentContent = new(CreateBytes(16));
NormalizedTrackSegmentDataDto segment = _normalizedTrackSegmentDataDtoFixture.Create(content: segmentContent, startSeconds: 3.25m);
_mockHandler.HandleAsync(Arg.Any<GetTrackSegmentQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(segment));
SetRouteValues();
try
{
CultureInfo.CurrentCulture = new CultureInfo("de-DE");
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
Assert.Equal("3.25", _sut.HttpContext.Response.Headers["X-Segment-Start-Seconds"].ToString());
}
finally
{
CultureInfo.CurrentCulture = previousCulture;
}
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult()
{
// Arrange
List<Error> errors = [DomainErrors.Playback.DeliveryIdIsInvalid, DomainErrors.Playback.SegmentIndexMustBeValid];
_mockHandler.HandleAsync(Arg.Any<GetTrackSegmentQuery>(), Arg.Any<CancellationToken>())
.Returns(errors);
SetRouteValues();
// Act
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemResult.StatusCode);
Assert.Equal("application/problem+json", problemResult.ContentType);
HttpValidationProblemDetails validationProblemDetails = Assert.IsType<HttpValidationProblemDetails>(problemResult.ProblemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status);
Assert.Equal("General.Validation", validationProblemDetails.Title);
Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail);
Assert.Contains("General.Validation", validationProblemDetails.Errors.Keys);
Assert.Contains("DeliveryIdIsInvalid", validationProblemDetails.Errors["General.Validation"]);
Assert.Contains("SegmentIndexMustBeValid", validationProblemDetails.Errors["General.Validation"]);
}
[Theory]
[InlineData("NotFound", StatusCodes.Status404NotFound)] // the delivery, track or segment does not exist
[InlineData("Conflict", StatusCodes.Status409Conflict)] // the delivery changed since the manifest declared it
[InlineData("ResourceUnavailable", StatusCodes.Status503ServiceUnavailable)] // the normalization pipeline is temporarily unavailable
public async Task ExecuteAsync_WhenHandlerReturnsAProblemError_ShouldReturnTheMappedStatusCode(string errorKind, int expectedStatusCode)
{
// Arrange
Error error = errorKind switch
{
"NotFound" => DomainErrors.Music.TrackFileNotFound,
"Conflict" => DomainErrors.Playback.PlaybackDeliveryChanged,
_ => DomainErrors.Playback.NormalizationUnavailable,
};
_mockHandler.HandleAsync(Arg.Any<GetTrackSegmentQuery>(), Arg.Any<CancellationToken>())
.Returns(error);
SetRouteValues();
// Act
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(expectedStatusCode, problemResult.StatusCode);
Assert.Equal(expectedStatusCode, problemResult.ProblemDetails.Status);
Assert.Equal(error.Code, problemResult.ProblemDetails.Title);
Assert.Equal(error.Description, problemResult.ProblemDetails.Detail);
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldSendTheExactRouteValuesToTheHandler()
{
// Arrange
string libraryId = "11111111-1111-1111-1111-111111111111";
string artistId = "22222222-2222-2222-2222-222222222222";
string albumId = "33333333-3333-3333-3333-333333333333";
string trackId = "44444444-4444-4444-4444-444444444444";
string deliveryId = "0123456789abcdef0123456789abcdef";
string segmentIndex = "7";
_mockHandler.HandleAsync(Arg.Any<GetTrackSegmentQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_normalizedTrackSegmentDataDtoFixture.Create()));
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId;
_sut.HttpContext.Request.RouteValues["artistId"] = artistId;
_sut.HttpContext.Request.RouteValues["albumId"] = albumId;
_sut.HttpContext.Request.RouteValues["trackId"] = trackId;
_sut.HttpContext.Request.RouteValues["deliveryId"] = deliveryId;
_sut.HttpContext.Request.RouteValues["segmentIndex"] = segmentIndex;
CancellationToken cancellationToken = CancellationToken.None;
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<GetTrackSegmentQuery>(query =>
query.LibraryId == libraryId &&
query.ArtistId == artistId &&
query.AlbumId == albumId &&
query.TrackId == trackId &&
query.DeliveryId == deliveryId &&
query.SegmentIndex == segmentIndex),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendNullRouteValuesToTheHandler()
{
// Arrange
_mockHandler.HandleAsync(Arg.Any<GetTrackSegmentQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_normalizedTrackSegmentDataDtoFixture.Create()));
_sut.HttpContext.Request.RouteValues.Clear();
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<GetTrackSegmentQuery>(query =>
query.LibraryId == null &&
query.ArtistId == null &&
query.AlbumId == null &&
query.TrackId == null &&
query.DeliveryId == null &&
query.SegmentIndex == null),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
CancellationTokenSource cancellationTokenSource = new();
TaskCompletionSource<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
_mockHandler.HandleAsync(Arg.Any<GetTrackSegmentQuery>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Task.Run(async () =>
{
operationStarted.SetResult(true);
await cancellationRequested.Task;
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From(_normalizedTrackSegmentDataDtoFixture.Create());
}, callInfo.Arg<CancellationToken>()));
SetRouteValues();
// Act
Task<IResult> operationTask = _sut.ExecuteAsync(EmptyRequest.Instance, cancellationTokenSource.Token);
await operationStarted.Task;
cancellationTokenSource.Cancel();
cancellationRequested.SetResult(true);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
}
/// <summary>
/// Sets the six route values the endpoint reads from the route.
/// </summary>
private void SetRouteValues()
{
_sut.HttpContext.Request.RouteValues["libraryId"] = Guid.NewGuid().ToString();
_sut.HttpContext.Request.RouteValues["artistId"] = Guid.NewGuid().ToString();
_sut.HttpContext.Request.RouteValues["albumId"] = Guid.NewGuid().ToString();
_sut.HttpContext.Request.RouteValues["trackId"] = Guid.NewGuid().ToString();
_sut.HttpContext.Request.RouteValues["deliveryId"] = Guid.NewGuid().ToString("N");
_sut.HttpContext.Request.RouteValues["segmentIndex"] = "0";
}
/// <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))];
}
}
@@ -40,6 +40,7 @@
<ItemGroup>
<ProjectReference Include="..\..\..\src\Lumina.Presentation.Api\Lumina.Presentation.Api.csproj" />
<ProjectReference Include="..\..\Common\Lumina.Application.Fixtures\Lumina.Application.Fixtures.csproj" />
<ProjectReference Include="..\..\Common\Lumina.Contracts.Fixtures\Lumina.Contracts.Fixtures.csproj" />
<ProjectReference Include="..\..\Common\Lumina.Presentation.Api.Fixtures\Lumina.Presentation.Api.Fixtures.csproj" />
</ItemGroup>
@@ -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))];
}
}
@@ -0,0 +1,57 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Playback;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Common.Playback;
/// <summary>
/// Contains unit tests for the <see cref="PlaybackDeliveryId"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class PlaybackDeliveryIdTests
{
[Theory]
[InlineData("0123456789abcdef0123456789abcdef")] // a lowercase hexadecimal handle
[InlineData("ffffffffffffffffffffffffffffffff")] // an all lowercase hexadecimal handle
[InlineData("00000000000000000000000000000000")] // an all zero handle
[InlineData("8f14e45fceea167a5a36dedd4bea2543")] // a random lowercase hexadecimal handle
public void IsValid_WhenValueIsThirtyTwoLowercaseHexadecimalCharacters_ShouldReturnTrue(string value)
{
// Act
bool result = PlaybackDeliveryId.IsValid(value);
// Assert
Assert.True(result);
}
[Theory]
[InlineData(null)] // an absent handle is not valid
[InlineData("")] // an empty handle is not valid
[InlineData(" ")] // a whitespace only handle is not valid
[InlineData("0123456789abcdef0123456789abcde")] // a handle with 31 characters is too short
[InlineData("0123456789abcdef0123456789abcdef0")] // a handle with 33 characters is too long
[InlineData("0123456789ABCDEF0123456789ABCDEF")] // an uppercase handle is not accepted
[InlineData("01234567-89ab-cdef-0123-456789abcdef")] // a dashed GUID is not accepted
[InlineData("0123456789abcdef0123456789abcdeg")] // a non hexadecimal handle is not accepted
[InlineData("0123456789abcdef0123456789abcde ")] // a handle with a trailing space is not accepted
public void IsValid_WhenValueDoesNotMatchTheHandleFormat_ShouldReturnFalse(string? value)
{
// Act
bool result = PlaybackDeliveryId.IsValid(value);
// Assert
Assert.False(result);
}
[Fact]
public void CharacterCount_ShouldBeThirtyTwo()
{
// Act
int characterCount = PlaybackDeliveryId.CHARACTER_COUNT;
// Assert
Assert.Equal(32, characterCount);
}
}
@@ -0,0 +1,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);
}
}
@@ -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))];
}
}
@@ -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))];
}
}