Adds deletion and restore for music library items.

This commit is contained in:
BinaryAlley committed 2026-11-15 18:53:10 +02:00
1 parent 98515dc5e8
commit f9ad8b2fc5
224 files changed
+22384 -1360

No files matched your search

@@ -0,0 +1,225 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.RestoreMusicAlbum;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Microsoft.AspNetCore.Http;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.RestoreMusicAlbum;
/// <summary>
/// Contains unit tests for the <see cref="RestoreMusicAlbumEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RestoreMusicAlbumEndpointTests
{
private readonly IApiHttpClient _mockApiHttpClient;
private readonly RestoreMusicAlbumEndpoint _sut;
/// <summary>
/// Initializes a new instance of the <see cref="RestoreMusicAlbumEndpointTests"/> class.
/// </summary>
public RestoreMusicAlbumEndpointTests()
{
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
// The restore endpoints forward a bodyless POST upstream; returning an empty request lets every test that is not about
// cancellation focus on the URL construction instead of repeating the upstream stub.
_mockApiHttpClient.PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
Arg.Any<string>(), Arg.Any<Web.Common.Requests.Common.EmptyRequest>(), Arg.Any<CancellationToken>())
.Returns(new Web.Common.Requests.Common.EmptyRequest());
_sut = Factory.Create<RestoreMusicAlbumEndpoint>(_mockApiHttpClient);
}
[Theory]
[InlineData("D")] // Standard hyphenated format.
[InlineData("B")] // Braced format.
[InlineData("N")] // Compact format.
[InlineData("P")] // Parenthesized format.
public async Task ExecuteAsync_WhenCalled_ShouldRestoreAlbumViaApiWithNormalizedIdsAndReturnSuccessPayload(string guidFormat)
{
// Arrange
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
Guid libraryId = Guid.NewGuid();
ConfigureRequest(artistId.ToString(guidFormat), albumId.ToString(guidFormat), libraryId.ToString(guidFormat));
// Act
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
// Assert
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
BuildExpectedEndpoint(libraryId, artistId, albumId),
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
Arg.Any<CancellationToken>());
using JsonDocument jsonDocument = JsonDocument.Parse(body);
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
Assert.True(jsonDocument.RootElement.GetProperty("data").GetProperty("isRestored").GetBoolean());
}
[Fact]
public async Task ExecuteAsync_WhenArtistRouteIdIsNotParseable_ShouldForwardGuidEmptyArtistIdToApi()
{
// Arrange
Guid albumId = Guid.NewGuid();
Guid libraryId = Guid.NewGuid();
ConfigureRequest("not-a-guid", albumId.ToString(), libraryId.ToString());
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
BuildExpectedEndpoint(libraryId, Guid.Empty, albumId),
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenArtistRouteIdIsMissing_ShouldForwardGuidEmptyArtistIdToApi()
{
// Arrange
Guid albumId = Guid.NewGuid();
Guid libraryId = Guid.NewGuid();
ConfigureRequest(null, albumId.ToString(), libraryId.ToString());
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
BuildExpectedEndpoint(libraryId, Guid.Empty, albumId),
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenAlbumRouteIdIsNotParseable_ShouldForwardGuidEmptyAlbumIdToApi()
{
// Arrange
Guid artistId = Guid.NewGuid();
Guid libraryId = Guid.NewGuid();
ConfigureRequest(artistId.ToString(), "not-a-guid", libraryId.ToString());
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
BuildExpectedEndpoint(libraryId, artistId, Guid.Empty),
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenAlbumRouteIdIsMissing_ShouldForwardGuidEmptyAlbumIdToApi()
{
// Arrange
Guid artistId = Guid.NewGuid();
Guid libraryId = Guid.NewGuid();
ConfigureRequest(artistId.ToString(), null, libraryId.ToString());
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
BuildExpectedEndpoint(libraryId, artistId, Guid.Empty),
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenLibraryQueryIdIsNotParseable_ShouldForwardGuidEmptyLibraryIdToApi()
{
// Arrange
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
ConfigureRequest(artistId.ToString(), albumId.ToString(), "not-a-guid");
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
BuildExpectedEndpoint(Guid.Empty, artistId, albumId),
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenLibraryQueryIdIsMissing_ShouldForwardGuidEmptyLibraryIdToApi()
{
// Arrange
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
ConfigureRequest(artistId.ToString(), albumId.ToString(), null);
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
BuildExpectedEndpoint(Guid.Empty, artistId, albumId),
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
Guid libraryId = Guid.NewGuid();
ConfigureRequest(artistId.ToString(), albumId.ToString(), libraryId.ToString());
using CancellationTokenSource cancellationTokenSource = new();
cancellationTokenSource.Cancel();
_mockApiHttpClient.PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
Arg.Any<string>(), Arg.Any<Web.Common.Requests.Common.EmptyRequest>(), Arg.Any<CancellationToken>())
.Returns(Task.FromCanceled<Web.Common.Requests.Common.EmptyRequest>(cancellationTokenSource.Token));
// Act & Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(
() => _sut.ExecuteAsync(EmptyRequest.Instance, cancellationTokenSource.Token));
}
/// <summary>
/// Sets the route and query values the endpoint reads the album identity from.
/// </summary>
/// <param name="artistId">The raw route value of the artist Id, or <see langword="null"/> to leave the route value missing.</param>
/// <param name="albumId">The raw route value of the album Id, or <see langword="null"/> to leave the route value missing.</param>
/// <param name="libraryId">The raw query value of the library Id, or <see langword="null"/> to leave the query string missing.</param>
private void ConfigureRequest(string? artistId, string? albumId, string? libraryId)
{
if (artistId is not null)
_sut.HttpContext.Request.RouteValues["artistId"] = artistId;
if (albumId is not null)
_sut.HttpContext.Request.RouteValues["albumId"] = albumId;
if (libraryId is not null)
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={libraryId}");
}
/// <summary>
/// Builds the upstream endpoint the album restoration is expected to be sent to.
/// </summary>
/// <param name="libraryId">The normalized Id of the media library.</param>
/// <param name="artistId">The normalized Id of the artist.</param>
/// <param name="albumId">The normalized Id of the album.</param>
/// <returns>The expected upstream endpoint.</returns>
private static string BuildExpectedEndpoint(Guid libraryId, Guid artistId, Guid albumId)
{
return ApiRoutes.Music.RESTORE_ALBUM
.Replace("{libraryId}", libraryId.ToString())
.Replace("{artistId}", artistId.ToString())
.Replace("{albumId}", albumId.ToString());
}
}
@@ -91,6 +91,7 @@ public class MusicArtistsIndexViewEndpointTests
_mockUrlService.GetAbsoluteUrl(WebRoutes.Settings.GET_USER_SETTINGS).Returns("http://localhost/en-us/tools/settings/api-get-user-settings");
_mockUrlService.GetAbsoluteUrl(WebRoutes.Music.ARTIST, Arg.Any<object>()).Returns("http://localhost/en-us/library/audio-library/music-library/artists/00000000-0000-0000-0000-000000000000");
_mockUrlService.GetAbsoluteUrl(WebRoutes.Music.DELETE_ARTIST, Arg.Any<object>()).Returns("http://localhost/en-us/library/audio-library/music-library/artists/00000000-0000-0000-0000-000000000000/api-delete-artist");
_mockUrlService.GetAbsoluteUrl(WebRoutes.Music.DELETED_MUSIC_ITEMS).Returns("http://localhost/en-us/library/audio-library/music-library/deleted-items");
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_themePageRenderResultDtoFixture.Create(content: "<section>content</section>", script: "<script>script</script>")));
@@ -120,6 +121,10 @@ public class MusicArtistsIndexViewEndpointTests
string.Equals(
page.PageData["deleteUrl"] as string,
"http://localhost/en-us/library/audio-library/music-library/artists/00000000-0000-0000-0000-000000000000/api-delete-artist",
StringComparison.Ordinal) &&
string.Equals(
page.PageData["deletedItemsUrl"] as string,
"http://localhost/en-us/library/audio-library/music-library/deleted-items",
StringComparison.Ordinal)),
Arg.Is<string?>(requestedThemeId => requestedThemeId == null),
Arg.Any<CancellationToken>());
@@ -0,0 +1,178 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.RestoreMusicArtist;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Microsoft.AspNetCore.Http;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.RestoreMusicArtist;
/// <summary>
/// Contains unit tests for the <see cref="RestoreMusicArtistEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RestoreMusicArtistEndpointTests
{
private readonly IApiHttpClient _mockApiHttpClient;
private readonly RestoreMusicArtistEndpoint _sut;
/// <summary>
/// Initializes a new instance of the <see cref="RestoreMusicArtistEndpointTests"/> class.
/// </summary>
public RestoreMusicArtistEndpointTests()
{
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
// The restore endpoints forward a bodyless POST upstream; returning an empty request lets every test that is not about
// cancellation focus on the URL construction instead of repeating the upstream stub.
_mockApiHttpClient.PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
Arg.Any<string>(), Arg.Any<Web.Common.Requests.Common.EmptyRequest>(), Arg.Any<CancellationToken>())
.Returns(new Web.Common.Requests.Common.EmptyRequest());
_sut = Factory.Create<RestoreMusicArtistEndpoint>(_mockApiHttpClient);
}
[Theory]
[InlineData("D")] // Standard hyphenated format.
[InlineData("B")] // Braced format.
[InlineData("N")] // Compact format.
[InlineData("P")] // Parenthesized format.
public async Task ExecuteAsync_WhenCalled_ShouldRestoreArtistViaApiWithNormalizedIdsAndReturnSuccessPayload(string guidFormat)
{
// Arrange
Guid artistId = Guid.NewGuid();
Guid libraryId = Guid.NewGuid();
ConfigureRequest(artistId.ToString(guidFormat), libraryId.ToString(guidFormat));
// Act
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
// Assert
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
BuildExpectedEndpoint(libraryId, artistId),
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
Arg.Any<CancellationToken>());
using JsonDocument jsonDocument = JsonDocument.Parse(body);
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
Assert.True(jsonDocument.RootElement.GetProperty("data").GetProperty("isRestored").GetBoolean());
}
[Fact]
public async Task ExecuteAsync_WhenArtistRouteIdIsNotParseable_ShouldForwardGuidEmptyArtistIdToApi()
{
// Arrange
Guid libraryId = Guid.NewGuid();
ConfigureRequest("not-a-guid", libraryId.ToString());
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
BuildExpectedEndpoint(libraryId, Guid.Empty),
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenArtistRouteIdIsMissing_ShouldForwardGuidEmptyArtistIdToApi()
{
// Arrange
Guid libraryId = Guid.NewGuid();
ConfigureRequest(null, libraryId.ToString());
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
BuildExpectedEndpoint(libraryId, Guid.Empty),
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenLibraryQueryIdIsNotParseable_ShouldForwardGuidEmptyLibraryIdToApi()
{
// Arrange
Guid artistId = Guid.NewGuid();
ConfigureRequest(artistId.ToString(), "not-a-guid");
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
BuildExpectedEndpoint(Guid.Empty, artistId),
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenLibraryQueryIdIsMissing_ShouldForwardGuidEmptyLibraryIdToApi()
{
// Arrange
Guid artistId = Guid.NewGuid();
ConfigureRequest(artistId.ToString(), null);
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
BuildExpectedEndpoint(Guid.Empty, artistId),
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
Guid artistId = Guid.NewGuid();
Guid libraryId = Guid.NewGuid();
ConfigureRequest(artistId.ToString(), libraryId.ToString());
using CancellationTokenSource cancellationTokenSource = new();
cancellationTokenSource.Cancel();
_mockApiHttpClient.PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
Arg.Any<string>(), Arg.Any<Web.Common.Requests.Common.EmptyRequest>(), Arg.Any<CancellationToken>())
.Returns(Task.FromCanceled<Web.Common.Requests.Common.EmptyRequest>(cancellationTokenSource.Token));
// Act & Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(
() => _sut.ExecuteAsync(EmptyRequest.Instance, cancellationTokenSource.Token));
}
/// <summary>
/// Sets the route and query values the endpoint reads the artist identity from.
/// </summary>
/// <param name="artistId">The raw route value of the artist Id, or <see langword="null"/> to leave the route value missing.</param>
/// <param name="libraryId">The raw query value of the library Id, or <see langword="null"/> to leave the query string missing.</param>
private void ConfigureRequest(string? artistId, string? libraryId)
{
if (artistId is not null)
_sut.HttpContext.Request.RouteValues["artistId"] = artistId;
if (libraryId is not null)
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={libraryId}");
}
/// <summary>
/// Builds the upstream endpoint the artist restoration is expected to be sent to.
/// </summary>
/// <param name="libraryId">The normalized Id of the media library.</param>
/// <param name="artistId">The normalized Id of the artist.</param>
/// <returns>The expected upstream endpoint.</returns>
private static string BuildExpectedEndpoint(Guid libraryId, Guid artistId)
{
return ApiRoutes.Music.RESTORE_ARTIST
.Replace("{libraryId}", libraryId.ToString())
.Replace("{artistId}", artistId.ToString());
}
}
@@ -0,0 +1,345 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
using Lumina.Presentation.Web.Common.DTO.Libraries;
using Lumina.Presentation.Web.Common.DTO.Themes;
using Lumina.Presentation.Web.Common.Http;
using Lumina.Presentation.Web.Common.Primitives;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Common.Services;
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.DeletedMusicItems;
using Lumina.Presentation.Web.Core.Themes;
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries;
using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes;
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Artists;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.Extensions.Localization;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.DeletedMusicItems;
/// <summary>
/// Contains unit tests for the <see cref="DeletedMusicItemsViewEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeletedMusicItemsViewEndpointTests
{
private const string ZERO_GUID = "00000000-0000-0000-0000-000000000000";
private readonly IApiHttpClient _mockApiHttpClient;
private readonly IUrlService _mockUrlService;
private readonly ThemePageRenderer _mockThemePageRenderer;
private readonly IAntiforgery _mockAntiforgery;
private readonly IStringLocalizerFactory _mockStringLocalizerFactory;
private readonly IStringLocalizer _mockStringLocalizer;
private readonly DeletedMusicItemsViewEndpoint _sut;
private readonly LibraryDtoFixture _libraryDtoFixture = new();
private readonly DeletedMusicArtistDtoFixture _deletedMusicArtistDtoFixture = new();
private readonly DeletedMusicAlbumDtoFixture _deletedMusicAlbumDtoFixture = new();
private readonly DeletedMusicTrackDtoFixture _deletedMusicTrackDtoFixture = new();
private readonly DeletedMusicItemsPageDtoFixture _deletedMusicItemsPageDtoFixture = new();
private readonly GetMusicArtistsViewRequestFixture _getMusicArtistsViewRequestFixture = new();
private readonly ThemePageRenderResultDtoFixture _themePageRenderResultDtoFixture = new();
private readonly List<object?> _artistRestoreRouteValues = [];
private readonly List<object?> _albumRestoreRouteValues = [];
private readonly List<object?> _trackRestoreRouteValues = [];
/// <summary>
/// Initializes a new instance of the <see cref="DeletedMusicItemsViewEndpointTests"/> class.
/// </summary>
public DeletedMusicItemsViewEndpointTests()
{
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
_mockUrlService = Substitute.For<IUrlService>();
_mockThemePageRenderer = Substitute.For<ThemePageRenderer>(new ThemeService(_mockApiHttpClient), new ThemeTemplateEngine());
_mockAntiforgery = Substitute.For<IAntiforgery>();
_mockAntiforgery.GetAndStoreTokens(Arg.Any<HttpContext>())
.Returns(new AntiforgeryTokenSet("request-token", "cookie-token", "__RequestVerificationToken", "RequestVerificationToken"));
_mockStringLocalizer = Substitute.For<IStringLocalizer>();
_mockStringLocalizer[Arg.Any<string>()].Returns(callInfo => new LocalizedString(
callInfo.Arg<string>(),
callInfo.Arg<string>() == "Title" ? "Deleted items" : $"Localized-{callInfo.Arg<string>()}"));
_mockStringLocalizer.GetAllStrings(Arg.Any<bool>()).Returns(
[
new("Title", "Deleted items"),
new("BackToLibrary", "Back to library"),
new("NoDeletedItems", "There are no deleted items in this library."),
new("Artists", "Artists"),
new("Albums", "Albums"),
new("Tracks", "Tracks"),
new("Name", "Name"),
new("Artist", "Artist"),
new("Album", "Album"),
new("TrackTitle", "Title"),
new("DeletedOn", "Deleted on"),
new("Restore", "Restore"),
new("Restored", "The item was restored."),
new("RestoreFailed", "The item could not be restored.")
]);
_mockStringLocalizerFactory = Substitute.For<IStringLocalizerFactory>();
_mockStringLocalizerFactory.Create(Arg.Any<string>(), Arg.Any<string>()).Returns(_mockStringLocalizer);
_sut = Factory.Create<DeletedMusicItemsViewEndpoint>(_mockApiHttpClient, _mockUrlService, _mockThemePageRenderer, _mockAntiforgery, _mockStringLocalizerFactory);
TestHttpContextFactory.ConfigureSession(_sut.HttpContext, TestHttpContextFactory.CreateSession());
_sut.HttpContext.Request.Path = "/en-us/library/audio-library/music-library/deleted-items";
StubUrls();
}
[Fact]
public async Task ExecuteAsync_WhenThemeRenderingSucceeds_ShouldRenderThemedViewWithDocumentedPageData()
{
// Arrange
LibraryDto library = _libraryDtoFixture.Create(title: "Music");
DeletedMusicArtistDto[] deletedArtists = [.. _deletedMusicArtistDtoFixture.CreateMany(2)];
DeletedMusicAlbumDto[] deletedAlbums = [.. _deletedMusicAlbumDtoFixture.CreateMany(2)];
DeletedMusicTrackDto[] deletedTracks = [.. _deletedMusicTrackDtoFixture.CreateMany(2)];
Guid libraryId = library.Id!.Value;
_mockApiHttpClient.GetAsync<LibraryDto>(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(library);
_mockApiHttpClient.GetAsync<DeletedMusicArtistDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(deletedArtists);
_mockApiHttpClient.GetAsync<DeletedMusicAlbumDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(deletedAlbums);
_mockApiHttpClient.GetAsync<DeletedMusicTrackDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(deletedTracks);
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_themePageRenderResultDtoFixture.Create(content: "<section>deleted</section>", script: "<script>deleted</script>")));
// Act
IResult result = await _sut.ExecuteAsync(_getMusicArtistsViewRequestFixture.Create(libraryId: libraryId), CancellationToken.None);
// Assert
Assert.Equal("/Core/Views/Shared/_ThemedView.cshtml", GetRenderedViewName(result));
await _mockApiHttpClient.Received(1).GetAsync<LibraryDto>(
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Libraries.GET_LIBRARY_BY_ID.Replace("{id}", libraryId.ToString())),
Arg.Any<CancellationToken>());
await _mockApiHttpClient.Received(1).GetAsync<DeletedMusicArtistDto[]>(
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Music.GET_DELETED_ARTISTS.Replace("{libraryId}", libraryId.ToString())),
Arg.Any<CancellationToken>());
await _mockApiHttpClient.Received(1).GetAsync<DeletedMusicAlbumDto[]>(
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Music.GET_DELETED_ALBUMS.Replace("{libraryId}", libraryId.ToString())),
Arg.Any<CancellationToken>());
await _mockApiHttpClient.Received(1).GetAsync<DeletedMusicTrackDto[]>(
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Music.GET_DELETED_TRACKS.Replace("{libraryId}", libraryId.ToString())),
Arg.Any<CancellationToken>());
await _mockThemePageRenderer.Received(1).RenderAsync(
Arg.Is<ThemePageDto>(page =>
page.PageKey == "library/audio-library/music-library/deleted-items" &&
page.Title == "Deleted items" &&
page.Description == string.Empty &&
string.Equals(page.PageData["libraryId"] as string, libraryId.ToString(), StringComparison.Ordinal) &&
string.Equals(page.PageData["libraryTitle"] as string, "Music", StringComparison.Ordinal) &&
string.Equals(page.PageData["artistRestoreUrl"] as string, $"http://localhost/en-us/library/audio-library/music-library/artists/{ZERO_GUID}/api-restore-artist", StringComparison.Ordinal) &&
string.Equals(page.PageData["albumRestoreUrl"] as string, $"http://localhost/en-us/library/audio-library/music-library/artists/{ZERO_GUID}/albums/{ZERO_GUID}/api-restore-album", StringComparison.Ordinal) &&
string.Equals(page.PageData["trackRestoreUrl"] as string, $"http://localhost/en-us/library/audio-library/music-library/artists/{ZERO_GUID}/albums/{ZERO_GUID}/tracks/{ZERO_GUID}/api-restore-track", StringComparison.Ordinal) &&
string.Equals(page.PageData["backUrl"] as string, $"http://localhost/en-us/library/audio-library/music-library/artists?libraryId={libraryId}", StringComparison.Ordinal) &&
string.Equals(page.PageData["antiforgeryToken"] as string, "request-token", StringComparison.Ordinal) &&
HasDocumentedDeletedMusicItems(page, deletedArtists, deletedAlbums, deletedTracks) &&
HasDocumentedLocalizedStrings(page)),
Arg.Is<string?>(requestedThemeId => requestedThemeId == null),
Arg.Any<CancellationToken>());
_mockAntiforgery.Received(1).GetAndStoreTokens(_sut.HttpContext);
}
[Fact]
public async Task ExecuteAsync_WhenLibraryIdIsNull_ShouldRedirectToHome()
{
// Arrange
_mockUrlService.GetAbsoluteUrl(WebRoutes.Home.INDEX_CULTURED).Returns("http://localhost/en-us");
// Act
IResult result = await _sut.ExecuteAsync(_getMusicArtistsViewRequestFixture.Create(libraryId: null), CancellationToken.None);
// Assert
RedirectHttpResult redirectResult = Assert.IsType<RedirectHttpResult>(result);
Assert.Equal("http://localhost/en-us", redirectResult.Url);
await _mockApiHttpClient.DidNotReceive().GetAsync<LibraryDto>(Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockApiHttpClient.DidNotReceive().GetAsync<DeletedMusicArtistDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockApiHttpClient.DidNotReceive().GetAsync<DeletedMusicAlbumDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockApiHttpClient.DidNotReceive().GetAsync<DeletedMusicTrackDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockThemePageRenderer.DidNotReceive().RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
_mockAntiforgery.DidNotReceive().GetAndStoreTokens(Arg.Any<HttpContext>());
}
[Fact]
public async Task ExecuteAsync_WhenThemeRenderingFails_ShouldFallBackToTheRazorViewWithTheDeletedMusicItems()
{
// Arrange
LibraryDto library = _libraryDtoFixture.Create(title: "Music");
DeletedMusicArtistDto[] deletedArtists = [.. _deletedMusicArtistDtoFixture.CreateMany(2)];
DeletedMusicAlbumDto[] deletedAlbums = [.. _deletedMusicAlbumDtoFixture.CreateMany(2)];
DeletedMusicTrackDto[] deletedTracks = [.. _deletedMusicTrackDtoFixture.CreateMany(2)];
_mockApiHttpClient.GetAsync<LibraryDto>(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(library);
_mockApiHttpClient.GetAsync<DeletedMusicArtistDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(deletedArtists);
_mockApiHttpClient.GetAsync<DeletedMusicAlbumDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(deletedAlbums);
_mockApiHttpClient.GetAsync<DeletedMusicTrackDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(deletedTracks);
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
.Returns(Result<ThemePageRenderResultDto>.Failure(Error.Failure("Theme.Render", "The page could not be rendered.")));
// Act
IResult result = await _sut.ExecuteAsync(_getMusicArtistsViewRequestFixture.Create(libraryId: library.Id), CancellationToken.None);
// Assert
Assert.Equal("/Core/Views/Library/AudioLibrary/MusicLibrary/DeletedItems.cshtml", GetRenderedViewName(result));
DeletedMusicItemsPageDto expectedPage = _deletedMusicItemsPageDtoFixture.Create(
library: library,
deletedArtists: deletedArtists,
deletedAlbums: deletedAlbums,
deletedTracks: deletedTracks);
DeletedMusicItemsPageDto model = Assert.IsType<DeletedMusicItemsPageDto>(GetRenderedModel(result));
Assert.Equal(expectedPage, model);
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldUseTheAllZeroGuidTemplatesOfTheRestoreRoutes()
{
// Arrange
LibraryDto library = _libraryDtoFixture.Create(title: "Music");
_mockApiHttpClient.GetAsync<LibraryDto>(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(library);
_mockApiHttpClient.GetAsync<DeletedMusicArtistDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(Array.Empty<DeletedMusicArtistDto>());
_mockApiHttpClient.GetAsync<DeletedMusicAlbumDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(Array.Empty<DeletedMusicAlbumDto>());
_mockApiHttpClient.GetAsync<DeletedMusicTrackDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(Array.Empty<DeletedMusicTrackDto>());
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_themePageRenderResultDtoFixture.Create()));
// Act
await _sut.ExecuteAsync(_getMusicArtistsViewRequestFixture.Create(libraryId: library.Id), CancellationToken.None);
// Assert
// The themed page replaces each all-zero Guid placeholder of the restore URLs one at a time, so every route value must be an empty Guid.
Assert.Single(_artistRestoreRouteValues);
AssertRouteValueIsEmptyGuid(_artistRestoreRouteValues[0], "artistId");
Assert.Single(_albumRestoreRouteValues);
AssertRouteValueIsEmptyGuid(_albumRestoreRouteValues[0], "artistId");
AssertRouteValueIsEmptyGuid(_albumRestoreRouteValues[0], "albumId");
Assert.Single(_trackRestoreRouteValues);
AssertRouteValueIsEmptyGuid(_trackRestoreRouteValues[0], "artistId");
AssertRouteValueIsEmptyGuid(_trackRestoreRouteValues[0], "albumId");
AssertRouteValueIsEmptyGuid(_trackRestoreRouteValues[0], "trackId");
}
/// <summary>
/// Stubs the absolute URLs that the endpoint resolves for the deleted music items page.
/// </summary>
private void StubUrls()
{
_mockUrlService.GetAbsoluteUrl(WebRoutes.Music.ARTISTS_INDEX).Returns("http://localhost/en-us/library/audio-library/music-library/artists");
_mockUrlService.GetAbsoluteUrl(WebRoutes.Music.RESTORE_ARTIST, Arg.Any<object?>())
.Returns(callInfo =>
{
_artistRestoreRouteValues.Add(callInfo.ArgAt<object?>(1));
return $"http://localhost/en-us/library/audio-library/music-library/artists/{ZERO_GUID}/api-restore-artist";
});
_mockUrlService.GetAbsoluteUrl(WebRoutes.Music.RESTORE_ALBUM, Arg.Any<object?>())
.Returns(callInfo =>
{
_albumRestoreRouteValues.Add(callInfo.ArgAt<object?>(1));
return $"http://localhost/en-us/library/audio-library/music-library/artists/{ZERO_GUID}/albums/{ZERO_GUID}/api-restore-album";
});
_mockUrlService.GetAbsoluteUrl(WebRoutes.Music.RESTORE_TRACK, Arg.Any<object?>())
.Returns(callInfo =>
{
_trackRestoreRouteValues.Add(callInfo.ArgAt<object?>(1));
return $"http://localhost/en-us/library/audio-library/music-library/artists/{ZERO_GUID}/albums/{ZERO_GUID}/tracks/{ZERO_GUID}/api-restore-track";
});
}
/// <summary>
/// Reads the private view name of the rendered <see cref="RazorViewResult"/>, which the result does not expose publicly.
/// </summary>
/// <param name="result">The result returned by the endpoint under test.</param>
/// <returns>The name or path of the rendered view.</returns>
private static string GetRenderedViewName(IResult result)
{
RazorViewResult viewResult = Assert.IsType<RazorViewResult>(result);
FieldInfo? viewNameField = typeof(RazorViewResult).GetField("_viewName", BindingFlags.Instance | BindingFlags.NonPublic);
Assert.NotNull(viewNameField);
return (string)viewNameField.GetValue(viewResult)!;
}
/// <summary>
/// Reads the private model of the rendered <see cref="RazorViewResult"/>, which the result does not expose publicly.
/// </summary>
/// <param name="result">The result returned by the endpoint under test.</param>
/// <returns>The model passed to the rendered view.</returns>
private static object? GetRenderedModel(IResult result)
{
RazorViewResult viewResult = Assert.IsType<RazorViewResult>(result);
FieldInfo? modelField = typeof(RazorViewResult).GetField("_model", BindingFlags.Instance | BindingFlags.NonPublic);
Assert.NotNull(modelField);
return modelField.GetValue(viewResult);
}
/// <summary>
/// Determines whether the page data carries the serialized deleted music items of the page.
/// </summary>
/// <param name="page">The page model passed to the theme renderer.</param>
/// <param name="deletedArtists">The deleted artists expected in the page data.</param>
/// <param name="deletedAlbums">The deleted albums expected in the page data.</param>
/// <param name="deletedTracks">The deleted tracks expected in the page data.</param>
/// <returns><see langword="true"/> when the serialized deleted items match the expected ones; otherwise <see langword="false"/>.</returns>
private static bool HasDocumentedDeletedMusicItems(
ThemePageDto page,
DeletedMusicArtistDto[] deletedArtists,
DeletedMusicAlbumDto[] deletedAlbums,
DeletedMusicTrackDto[] deletedTracks)
{
if (!page.PageData.TryGetValue("deletedArtistsJson", out object? artistsValue) || artistsValue is not string artistsJson)
return false;
if (!page.PageData.TryGetValue("deletedAlbumsJson", out object? albumsValue) || albumsValue is not string albumsJson)
return false;
if (!page.PageData.TryGetValue("deletedTracksJson", out object? tracksValue) || tracksValue is not string tracksJson)
return false;
using JsonDocument artistsDocument = JsonDocument.Parse(artistsJson);
using JsonDocument albumsDocument = JsonDocument.Parse(albumsJson);
using JsonDocument tracksDocument = JsonDocument.Parse(tracksJson);
return artistsDocument.RootElement.GetArrayLength() == deletedArtists.Length
&& string.Equals(artistsDocument.RootElement[0].GetProperty("name").GetString(), deletedArtists[0].Name, StringComparison.Ordinal)
&& albumsDocument.RootElement.GetArrayLength() == deletedAlbums.Length
&& string.Equals(albumsDocument.RootElement[0].GetProperty("title").GetString(), deletedAlbums[0].Title, StringComparison.Ordinal)
&& tracksDocument.RootElement.GetArrayLength() == deletedTracks.Length
&& string.Equals(tracksDocument.RootElement[0].GetProperty("albumTitle").GetString(), deletedTracks[0].AlbumTitle, StringComparison.Ordinal);
}
/// <summary>
/// Determines whether the page data carries the localized strings of the deleted music items page, both raw and serialized.
/// </summary>
/// <param name="page">The page model passed to the theme renderer.</param>
/// <returns><see langword="true"/> when the localized strings are exposed and serialized; otherwise <see langword="false"/>.</returns>
private static bool HasDocumentedLocalizedStrings(ThemePageDto page)
{
if (!page.PageData.TryGetValue("strings", out object? value) || value is not Dictionary<string, object?> strings)
return false;
if (!page.PageData.TryGetValue("stringsJson", out object? jsonValue) || jsonValue is not string stringsJson)
return false;
using JsonDocument stringsDocument = JsonDocument.Parse(stringsJson);
return string.Equals(strings["Title"] as string, "Deleted items", StringComparison.Ordinal)
&& string.Equals(strings["NoDeletedItems"] as string, "There are no deleted items in this library.", StringComparison.Ordinal)
&& string.Equals(stringsDocument.RootElement.GetProperty("title").GetString(), "Deleted items", StringComparison.Ordinal)
&& string.Equals(stringsDocument.RootElement.GetProperty("noDeletedItems").GetString(), "There are no deleted items in this library.", StringComparison.Ordinal);
}
/// <summary>
/// Asserts that the named property of an anonymous route values object is the empty Guid.
/// </summary>
/// <param name="routeValues">The anonymous route values object passed to the URL service.</param>
/// <param name="propertyName">The name of the route value property to check.</param>
private static void AssertRouteValueIsEmptyGuid(object? routeValues, string propertyName)
{
Assert.NotNull(routeValues);
PropertyInfo? property = routeValues!.GetType().GetProperty(propertyName);
Assert.NotNull(property);
Assert.Equal(Guid.Empty, (Guid)property!.GetValue(routeValues)!);
}
}
@@ -0,0 +1,276 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.RestoreMusicTrack;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Microsoft.AspNetCore.Http;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.RestoreMusicTrack;
/// <summary>
/// Contains unit tests for the <see cref="RestoreMusicTrackEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RestoreMusicTrackEndpointTests
{
private readonly IApiHttpClient _mockApiHttpClient;
private readonly RestoreMusicTrackEndpoint _sut;
/// <summary>
/// Initializes a new instance of the <see cref="RestoreMusicTrackEndpointTests"/> class.
/// </summary>
public RestoreMusicTrackEndpointTests()
{
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
// The restore endpoints forward a bodyless POST upstream; returning an empty request lets every test that is not about
// cancellation focus on the URL construction instead of repeating the upstream stub.
_mockApiHttpClient.PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
Arg.Any<string>(), Arg.Any<Web.Common.Requests.Common.EmptyRequest>(), Arg.Any<CancellationToken>())
.Returns(new Web.Common.Requests.Common.EmptyRequest());
_sut = Factory.Create<RestoreMusicTrackEndpoint>(_mockApiHttpClient);
}
[Theory]
[InlineData("D")] // Standard hyphenated format.
[InlineData("B")] // Braced format.
[InlineData("N")] // Compact format.
[InlineData("P")] // Parenthesized format.
public async Task ExecuteAsync_WhenCalled_ShouldRestoreTrackViaApiWithNormalizedIdsAndReturnSuccessPayload(string guidFormat)
{
// Arrange
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
Guid trackId = Guid.NewGuid();
Guid libraryId = Guid.NewGuid();
ConfigureRequest(artistId.ToString(guidFormat), albumId.ToString(guidFormat), trackId.ToString(guidFormat), libraryId.ToString(guidFormat));
// Act
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
// Assert
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
BuildExpectedEndpoint(libraryId, artistId, albumId, trackId),
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
Arg.Any<CancellationToken>());
using JsonDocument jsonDocument = JsonDocument.Parse(body);
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
Assert.True(jsonDocument.RootElement.GetProperty("data").GetProperty("isRestored").GetBoolean());
}
[Fact]
public async Task ExecuteAsync_WhenArtistRouteIdIsNotParseable_ShouldForwardGuidEmptyArtistIdToApi()
{
// Arrange
Guid albumId = Guid.NewGuid();
Guid trackId = Guid.NewGuid();
Guid libraryId = Guid.NewGuid();
ConfigureRequest("not-a-guid", albumId.ToString(), trackId.ToString(), libraryId.ToString());
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
BuildExpectedEndpoint(libraryId, Guid.Empty, albumId, trackId),
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenArtistRouteIdIsMissing_ShouldForwardGuidEmptyArtistIdToApi()
{
// Arrange
Guid albumId = Guid.NewGuid();
Guid trackId = Guid.NewGuid();
Guid libraryId = Guid.NewGuid();
ConfigureRequest(null, albumId.ToString(), trackId.ToString(), libraryId.ToString());
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
BuildExpectedEndpoint(libraryId, Guid.Empty, albumId, trackId),
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenAlbumRouteIdIsNotParseable_ShouldForwardGuidEmptyAlbumIdToApi()
{
// Arrange
Guid artistId = Guid.NewGuid();
Guid trackId = Guid.NewGuid();
Guid libraryId = Guid.NewGuid();
ConfigureRequest(artistId.ToString(), "not-a-guid", trackId.ToString(), libraryId.ToString());
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
BuildExpectedEndpoint(libraryId, artistId, Guid.Empty, trackId),
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenAlbumRouteIdIsMissing_ShouldForwardGuidEmptyAlbumIdToApi()
{
// Arrange
Guid artistId = Guid.NewGuid();
Guid trackId = Guid.NewGuid();
Guid libraryId = Guid.NewGuid();
ConfigureRequest(artistId.ToString(), null, trackId.ToString(), libraryId.ToString());
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
BuildExpectedEndpoint(libraryId, artistId, Guid.Empty, trackId),
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenTrackRouteIdIsNotParseable_ShouldForwardGuidEmptyTrackIdToApi()
{
// Arrange
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
Guid libraryId = Guid.NewGuid();
ConfigureRequest(artistId.ToString(), albumId.ToString(), "not-a-guid", libraryId.ToString());
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
BuildExpectedEndpoint(libraryId, artistId, albumId, Guid.Empty),
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenTrackRouteIdIsMissing_ShouldForwardGuidEmptyTrackIdToApi()
{
// Arrange
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
Guid libraryId = Guid.NewGuid();
ConfigureRequest(artistId.ToString(), albumId.ToString(), null, libraryId.ToString());
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
BuildExpectedEndpoint(libraryId, artistId, albumId, Guid.Empty),
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenLibraryQueryIdIsNotParseable_ShouldForwardGuidEmptyLibraryIdToApi()
{
// Arrange
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
Guid trackId = Guid.NewGuid();
ConfigureRequest(artistId.ToString(), albumId.ToString(), trackId.ToString(), "not-a-guid");
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
BuildExpectedEndpoint(Guid.Empty, artistId, albumId, trackId),
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenLibraryQueryIdIsMissing_ShouldForwardGuidEmptyLibraryIdToApi()
{
// Arrange
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
Guid trackId = Guid.NewGuid();
ConfigureRequest(artistId.ToString(), albumId.ToString(), trackId.ToString(), null);
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
BuildExpectedEndpoint(Guid.Empty, artistId, albumId, trackId),
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
Guid trackId = Guid.NewGuid();
Guid libraryId = Guid.NewGuid();
ConfigureRequest(artistId.ToString(), albumId.ToString(), trackId.ToString(), libraryId.ToString());
using CancellationTokenSource cancellationTokenSource = new();
cancellationTokenSource.Cancel();
_mockApiHttpClient.PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
Arg.Any<string>(), Arg.Any<Web.Common.Requests.Common.EmptyRequest>(), Arg.Any<CancellationToken>())
.Returns(Task.FromCanceled<Web.Common.Requests.Common.EmptyRequest>(cancellationTokenSource.Token));
// Act & Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(
() => _sut.ExecuteAsync(EmptyRequest.Instance, cancellationTokenSource.Token));
}
/// <summary>
/// Sets the route and query values the endpoint reads the track identity from.
/// </summary>
/// <param name="artistId">The raw route value of the artist Id, or <see langword="null"/> to leave the route value missing.</param>
/// <param name="albumId">The raw route value of the album Id, or <see langword="null"/> to leave the route value missing.</param>
/// <param name="trackId">The raw route value of the track Id, or <see langword="null"/> to leave the route value missing.</param>
/// <param name="libraryId">The raw query value of the library Id, or <see langword="null"/> to leave the query string missing.</param>
private void ConfigureRequest(string? artistId, string? albumId, string? trackId, string? libraryId)
{
if (artistId is not null)
_sut.HttpContext.Request.RouteValues["artistId"] = artistId;
if (albumId is not null)
_sut.HttpContext.Request.RouteValues["albumId"] = albumId;
if (trackId is not null)
_sut.HttpContext.Request.RouteValues["trackId"] = trackId;
if (libraryId is not null)
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={libraryId}");
}
/// <summary>
/// Builds the upstream endpoint the track restoration is expected to be sent to.
/// </summary>
/// <param name="libraryId">The normalized Id of the media library.</param>
/// <param name="artistId">The normalized Id of the artist.</param>
/// <param name="albumId">The normalized Id of the album.</param>
/// <param name="trackId">The normalized Id of the track.</param>
/// <returns>The expected upstream endpoint.</returns>
private static string BuildExpectedEndpoint(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)
{
return ApiRoutes.Music.RESTORE_TRACK
.Replace("{libraryId}", libraryId.ToString())
.Replace("{artistId}", artistId.ToString())
.Replace("{albumId}", albumId.ToString())
.Replace("{trackId}", trackId.ToString());
}
}