mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-02 20:11:10 +00:00
Implements tests for commit 525ac1348d
Covers the favorites feature and the playlist and favorite pagination changes with unit, integration and security tests, and fixtures for the new request, response, DTO and entity types. Also fixes the issues found while covering the commit: declares FavoriteMediaKind.None as the default value and rejects it in every favorite operation; queues the favorite added domain event only after the persisted favorite is read back; and preserves the private, no-store cache header on view pages after the antiforgery and session middlewares overwrite it.
This commit is contained in:
1 parent
468f1846f1
commit
394f6b510c
135 files changed
+19167
-13
No files matched your search
+164
@@ -0,0 +1,164 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Http;
|
||||
using Lumina.Presentation.Web.Common.Middlewares;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.Features;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Common.Middlewares;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="CacheControlHeaderMiddleware"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class CacheControlHeaderMiddlewareTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task InvokeAsync_WhenTheEndpointStoredACacheControlValue_ShouldRestoreItAfterLaterCallbacksRun()
|
||||
{
|
||||
// Arrange
|
||||
DefaultHttpContext context = new();
|
||||
TestHttpResponseFeature responseFeature = new();
|
||||
context.Features.Set<IHttpResponseFeature>(responseFeature);
|
||||
context.Items[HttpContextItemKeys.CACHE_CONTROL] = "private, no-store";
|
||||
CacheControlHeaderMiddleware sut = new(nextContext =>
|
||||
{
|
||||
// The session middleware registers its cache header write after this middleware, so it runs first when the response starts.
|
||||
nextContext.Response.OnStarting(() =>
|
||||
{
|
||||
nextContext.Response.Headers.CacheControl = "no-cache,no-store";
|
||||
return Task.CompletedTask;
|
||||
});
|
||||
return Task.CompletedTask;
|
||||
});
|
||||
|
||||
// Act
|
||||
await sut.InvokeAsync(context);
|
||||
await responseFeature.StartAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal("private, no-store", context.Response.Headers.CacheControl.ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InvokeAsync_WhenNoCacheControlValueWasStored_ShouldLeaveTheHeaderWrittenByLaterCallbacks()
|
||||
{
|
||||
// Arrange
|
||||
DefaultHttpContext context = new();
|
||||
TestHttpResponseFeature responseFeature = new();
|
||||
context.Features.Set<IHttpResponseFeature>(responseFeature);
|
||||
CacheControlHeaderMiddleware sut = new(nextContext =>
|
||||
{
|
||||
nextContext.Response.OnStarting(() =>
|
||||
{
|
||||
nextContext.Response.Headers.CacheControl = "no-cache,no-store";
|
||||
return Task.CompletedTask;
|
||||
});
|
||||
return Task.CompletedTask;
|
||||
});
|
||||
|
||||
// Act
|
||||
await sut.InvokeAsync(context);
|
||||
await responseFeature.StartAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal("no-cache,no-store", context.Response.Headers.CacheControl.ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InvokeAsync_WhenTheStoredValueIsEmpty_ShouldLeaveTheHeaderWrittenByLaterCallbacks()
|
||||
{
|
||||
// Arrange
|
||||
DefaultHttpContext context = new();
|
||||
TestHttpResponseFeature responseFeature = new();
|
||||
context.Features.Set<IHttpResponseFeature>(responseFeature);
|
||||
context.Items[HttpContextItemKeys.CACHE_CONTROL] = string.Empty;
|
||||
CacheControlHeaderMiddleware sut = new(nextContext =>
|
||||
{
|
||||
nextContext.Response.OnStarting(() =>
|
||||
{
|
||||
nextContext.Response.Headers.CacheControl = "no-cache,no-store";
|
||||
return Task.CompletedTask;
|
||||
});
|
||||
return Task.CompletedTask;
|
||||
});
|
||||
|
||||
// Act
|
||||
await sut.InvokeAsync(context);
|
||||
await responseFeature.StartAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal("no-cache,no-store", context.Response.Headers.CacheControl.ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Minimal response feature that stores the response-start callbacks and invokes them in reverse registration order, like the server does.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
private sealed class TestHttpResponseFeature : IHttpResponseFeature
|
||||
{
|
||||
private readonly List<(Func<object, Task> Callback, object State)> _onStartingCallbacks = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the status code of the response.
|
||||
/// </summary>
|
||||
public int StatusCode { get; set; } = StatusCodes.Status200OK;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the reason phrase of the response.
|
||||
/// </summary>
|
||||
public string? ReasonPhrase { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the headers of the response.
|
||||
/// </summary>
|
||||
public IHeaderDictionary Headers { get; set; } = new HeaderDictionary();
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the body of the response.
|
||||
/// </summary>
|
||||
public Stream Body { get; set; } = new MemoryStream();
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the response has started.
|
||||
/// </summary>
|
||||
public bool HasStarted { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Registers a callback to invoke when the response starts.
|
||||
/// </summary>
|
||||
/// <param name="callback">The callback to invoke.</param>
|
||||
/// <param name="state">The state passed to the callback.</param>
|
||||
public void OnStarting(Func<object, Task> callback, object state)
|
||||
{
|
||||
_onStartingCallbacks.Add((callback, state));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers a callback to invoke when the response completes.
|
||||
/// </summary>
|
||||
/// <param name="callback">The callback to invoke.</param>
|
||||
/// <param name="state">The state passed to the callback.</param>
|
||||
public void OnCompleted(Func<object, Task> callback, object state)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Starts the response and invokes the registered callbacks in reverse registration order.
|
||||
/// </summary>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
public async Task StartAsync()
|
||||
{
|
||||
if (HasStarted)
|
||||
return;
|
||||
HasStarted = true;
|
||||
for (int index = _onStartingCallbacks.Count - 1; index >= 0; index--)
|
||||
await _onStartingCallbacks[index].Callback(_onStartingCallbacks[index].State);
|
||||
}
|
||||
}
|
||||
}
|
||||
+57
@@ -83,6 +83,63 @@ public class BaseEndpointTests
|
||||
session.Received(1).Set(HttpContextItemKeys.LAST_DISPLAYED_VIEW, Arg.Any<byte[]>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TestSetCacheControl_WhenCalled_ShouldSetTheHeaderAndRememberTheValue()
|
||||
{
|
||||
// Act
|
||||
_sut.TestSetCacheControl("private, no-store");
|
||||
|
||||
// Assert
|
||||
Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers.CacheControl.ToString());
|
||||
Assert.Equal("private, no-store", _sut.HttpContext.Items[HttpContextItemKeys.CACHE_CONTROL]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TestView_WhenACacheControlValueWasRemembered_ShouldKeepItAfterALaterHeaderOverwrite()
|
||||
{
|
||||
// Arrange
|
||||
TestHttpContextFactory.ConfigureSession(_sut.HttpContext, TestHttpContextFactory.CreateSession());
|
||||
_sut.HttpContext.Request.Path = "/en-us/favorites";
|
||||
_sut.TestSetCacheControl("private, no-store");
|
||||
// The antiforgery token generation overwrites the header after the endpoint chose its value.
|
||||
_sut.HttpContext.Response.Headers.CacheControl = "no-cache, no-store";
|
||||
|
||||
// Act
|
||||
_sut.TestView("/Core/Views/Favorites/Index.cshtml");
|
||||
|
||||
// Assert
|
||||
Assert.Equal("private, no-store", _sut.HttpContext.Items[HttpContextItemKeys.CACHE_CONTROL]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TestView_WhenCacheControlIsSetDirectly_ShouldStoreItForTheResponseStartRestoration()
|
||||
{
|
||||
// Arrange
|
||||
TestHttpContextFactory.ConfigureSession(_sut.HttpContext, TestHttpContextFactory.CreateSession());
|
||||
_sut.HttpContext.Request.Path = "/en-us/favorites";
|
||||
_sut.HttpContext.Response.Headers.CacheControl = "private, no-store";
|
||||
|
||||
// Act
|
||||
_sut.TestView("/Core/Views/Favorites/Index.cshtml");
|
||||
|
||||
// Assert
|
||||
Assert.Equal("private, no-store", _sut.HttpContext.Items[HttpContextItemKeys.CACHE_CONTROL]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TestView_WhenCacheControlIsNotSet_ShouldNotStoreACacheControlValue()
|
||||
{
|
||||
// Arrange
|
||||
TestHttpContextFactory.ConfigureSession(_sut.HttpContext, TestHttpContextFactory.CreateSession());
|
||||
_sut.HttpContext.Request.Path = "/en-us/favorites";
|
||||
|
||||
// Act
|
||||
_sut.TestView("/Core/Views/Favorites/Index.cshtml");
|
||||
|
||||
// Assert
|
||||
Assert.False(_sut.HttpContext.Items.ContainsKey(HttpContextItemKeys.CACHE_CONTROL));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TestCulture_WhenCultureRouteValuePresent_ShouldReturnCulture()
|
||||
{
|
||||
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.Favorites;
|
||||
using Lumina.Presentation.Web.Common.Enums.Favorites;
|
||||
using Lumina.Presentation.Web.Common.Requests.Favorites;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Favorites.AddFavorite;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Favorites;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Favorites;
|
||||
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.Favorites.AddFavorite;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="AddFavoriteEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddFavoriteEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly AddFavoriteEndpoint _sut;
|
||||
private readonly AddFavoriteRequestFixture _addFavoriteRequestFixture = new();
|
||||
private readonly FavoriteDtoFixture _favoriteDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddFavoriteEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public AddFavoriteEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<AddFavoriteEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiSucceeds_ShouldReturnSuccessJsonWithTheCreatedFavorite()
|
||||
{
|
||||
// Arrange
|
||||
AddFavoriteRequest request = _addFavoriteRequestFixture.Create(
|
||||
mediaKind: FavoriteMediaKind.MusicTrack,
|
||||
mediaItemId: Guid.NewGuid());
|
||||
FavoriteDto expectedFavorite = _favoriteDtoFixture.Create(
|
||||
mediaKind: request.MediaKind!.Value,
|
||||
mediaItemId: request.MediaItemId!.Value);
|
||||
_mockApiHttpClient.PostAsync<FavoriteDto, AddFavoriteRequest>(Arg.Any<string>(), Arg.Any<AddFavoriteRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedFavorite);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
JsonElement data = jsonDocument.RootElement.GetProperty("data");
|
||||
Assert.Equal(expectedFavorite.Id, data.GetProperty("id").GetGuid());
|
||||
Assert.Equal((int)expectedFavorite.MediaKind, data.GetProperty("mediaKind").GetInt32());
|
||||
Assert.Equal(expectedFavorite.MediaItemId, data.GetProperty("mediaItemId").GetGuid());
|
||||
Assert.Equal(expectedFavorite.FavoritedOnUtc, data.GetProperty("favoritedOnUtc").GetDateTime());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldPostTheRequestPayloadOnceToTheDocumentedEndpoint()
|
||||
{
|
||||
// Arrange
|
||||
AddFavoriteRequest request = _addFavoriteRequestFixture.Create(
|
||||
mediaKind: FavoriteMediaKind.Book,
|
||||
mediaItemId: Guid.NewGuid());
|
||||
_mockApiHttpClient.PostAsync<FavoriteDto, AddFavoriteRequest>(Arg.Any<string>(), Arg.Any<AddFavoriteRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_favoriteDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostAsync<FavoriteDto, AddFavoriteRequest>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/me/favorites"),
|
||||
Arg.Is<AddFavoriteRequest>(payload =>
|
||||
payload.MediaKind == request.MediaKind &&
|
||||
payload.MediaItemId == request.MediaItemId),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
AddFavoriteRequest request = _addFavoriteRequestFixture.Create();
|
||||
FavoriteDto expectedFavorite = _favoriteDtoFixture.Create();
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
_mockApiHttpClient.PostAsync<FavoriteDto, AddFavoriteRequest>(Arg.Any<string>(), Arg.Any<AddFavoriteRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.ArgAt<CancellationToken>(2).ThrowIfCancellationRequested();
|
||||
return expectedFavorite;
|
||||
}, callInfo.ArgAt<CancellationToken>(2)));
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
}
|
||||
+212
@@ -0,0 +1,212 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.Favorites;
|
||||
using Lumina.Presentation.Web.Common.Enums.Favorites;
|
||||
using Lumina.Presentation.Web.Common.Requests.Favorites;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Favorites.GetFavoriteStatus;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Favorites;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Favorites;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Favorites.GetFavoriteStatus;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetFavoriteStatusEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetFavoriteStatusEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly GetFavoriteStatusEndpoint _sut;
|
||||
private readonly GetFavoriteStatusRequestFixture _getFavoriteStatusRequestFixture = new();
|
||||
private readonly FavoriteStatusDtoFixture _favoriteStatusDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetFavoriteStatusEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetFavoriteStatusEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<GetFavoriteStatusEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiSucceeds_ShouldReturnSuccessJsonWithTheFavoritedMediaItemIds()
|
||||
{
|
||||
// Arrange
|
||||
List<Guid> expectedIds = [Guid.NewGuid(), Guid.NewGuid()];
|
||||
GetFavoriteStatusRequest request = _getFavoriteStatusRequestFixture.Create(
|
||||
mediaKind: FavoriteMediaKind.MusicTrack,
|
||||
mediaItemIds: expectedIds);
|
||||
_mockApiHttpClient.GetAsync<FavoriteStatusDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_favoriteStatusDtoFixture.Create(favoritedMediaItemIds: expectedIds));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
JsonElement data = jsonDocument.RootElement.GetProperty("data");
|
||||
List<Guid> actualIds = [.. data.GetProperty("favoritedMediaItemIds").EnumerateArray().Select(element => element.GetGuid())];
|
||||
Assert.Equal(expectedIds, actualIds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenMediaKindAndIdsAreSupplied_ShouldForwardTheDocumentedQueryString()
|
||||
{
|
||||
// Arrange
|
||||
List<Guid> mediaItemIds = [Guid.NewGuid(), Guid.NewGuid()];
|
||||
GetFavoriteStatusRequest request = _getFavoriteStatusRequestFixture.Create(
|
||||
mediaKind: FavoriteMediaKind.MusicTrack,
|
||||
mediaItemIds: mediaItemIds);
|
||||
string expectedEndpoint = $"users/me/favorites/status?mediaKind=MusicTrack&mediaItemIds={mediaItemIds[0]}&mediaItemIds={mediaItemIds[1]}";
|
||||
_mockApiHttpClient.GetAsync<FavoriteStatusDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_favoriteStatusDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<FavoriteStatusDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == expectedEndpoint),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenMediaKindAndIdsAreOmitted_ShouldForwardTheBareStatusRoute()
|
||||
{
|
||||
// Arrange
|
||||
GetFavoriteStatusRequest request = _getFavoriteStatusRequestFixture.Create(
|
||||
includeMediaKind: false,
|
||||
includeMediaItemIds: false);
|
||||
_mockApiHttpClient.GetAsync<FavoriteStatusDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_favoriteStatusDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<FavoriteStatusDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/me/favorites/status"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenMediaKindIsOmitted_ShouldForwardOnlyTheIds()
|
||||
{
|
||||
// Arrange
|
||||
List<Guid> mediaItemIds = [Guid.NewGuid()];
|
||||
GetFavoriteStatusRequest request = _getFavoriteStatusRequestFixture.Create(
|
||||
mediaItemIds: mediaItemIds,
|
||||
includeMediaKind: false);
|
||||
_mockApiHttpClient.GetAsync<FavoriteStatusDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_favoriteStatusDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<FavoriteStatusDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == $"users/me/favorites/status?mediaItemIds={mediaItemIds[0]}"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenIdsAreOmitted_ShouldForwardOnlyTheMediaKind()
|
||||
{
|
||||
// Arrange
|
||||
GetFavoriteStatusRequest request = _getFavoriteStatusRequestFixture.Create(
|
||||
mediaKind: FavoriteMediaKind.Book,
|
||||
includeMediaItemIds: false);
|
||||
_mockApiHttpClient.GetAsync<FavoriteStatusDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_favoriteStatusDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<FavoriteStatusDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/me/favorites/status?mediaKind=Book"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenMoreThanTheMaximumIdsAreSupplied_ShouldForwardOnlyTheFirstOneHundredAndOne()
|
||||
{
|
||||
// Arrange
|
||||
List<Guid> mediaItemIds = [.. Enumerable.Range(1, 102).Select(index => new Guid(index, 0, 0, new byte[8]))];
|
||||
GetFavoriteStatusRequest request = _getFavoriteStatusRequestFixture.Create(
|
||||
mediaKind: FavoriteMediaKind.MusicTrack,
|
||||
mediaItemIds: mediaItemIds);
|
||||
string expectedIdsQuery = string.Join('&', mediaItemIds.Take(101).Select(mediaItemId => $"mediaItemIds={mediaItemId}"));
|
||||
string expectedEndpoint = $"users/me/favorites/status?mediaKind=MusicTrack&{expectedIdsQuery}";
|
||||
_mockApiHttpClient.GetAsync<FavoriteStatusDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_favoriteStatusDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<FavoriteStatusDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == expectedEndpoint),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockApiHttpClient.Received(1).GetAsync<FavoriteStatusDto>(
|
||||
Arg.Is<string>(endpoint => !endpoint.Contains(mediaItemIds[101].ToString(), StringComparison.Ordinal)),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSetPrivateNoStoreAndCookieVaryHeaders()
|
||||
{
|
||||
// Arrange
|
||||
_mockApiHttpClient.GetAsync<FavoriteStatusDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_favoriteStatusDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(_getFavoriteStatusRequestFixture.Create(), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString());
|
||||
Assert.Equal("Cookie", _sut.HttpContext.Response.Headers["Vary"].ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
FavoriteStatusDto expectedStatus = _favoriteStatusDtoFixture.Create();
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
_mockApiHttpClient.GetAsync<FavoriteStatusDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.ArgAt<CancellationToken>(1).ThrowIfCancellationRequested();
|
||||
return expectedStatus;
|
||||
}, callInfo.ArgAt<CancellationToken>(1)));
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(_getFavoriteStatusRequestFixture.Create(), cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
}
|
||||
+254
@@ -0,0 +1,254 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Common.DTO.Favorites;
|
||||
using Lumina.Presentation.Web.Common.Enums.Favorites;
|
||||
using Lumina.Presentation.Web.Common.Requests.Favorites;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Favorites.GetFavorites;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Favorites;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Favorites;
|
||||
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.Favorites.GetFavorites;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetFavoritesEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetFavoritesEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly GetFavoritesEndpoint _sut;
|
||||
private readonly GetFavoritesRequestFixture _getFavoritesRequestFixture = new();
|
||||
private readonly PaginatedDtoFixture<FavoriteItemDto> _paginatedDtoFixture = new();
|
||||
private readonly FavoriteItemDtoFixture _favoriteItemDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetFavoritesEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetFavoritesEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<GetFavoritesEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsFavorites_ShouldReturnSuccessJsonWithPaginatedFavorites()
|
||||
{
|
||||
// Arrange
|
||||
FavoriteItemDto expectedItem = _favoriteItemDtoFixture.Create(
|
||||
mediaKind: FavoriteMediaKind.MusicTrack,
|
||||
isAvailable: true,
|
||||
title: "Time",
|
||||
collectionTitle: "The Dark Side of the Moon",
|
||||
creatorName: "Pink Floyd",
|
||||
coverPath: "covers/dark-side-of-the-moon.jpg");
|
||||
PaginatedDto<FavoriteItemDto> expectedPage = _paginatedDtoFixture.Create(
|
||||
data: [expectedItem],
|
||||
currentPage: 2,
|
||||
perPage: 50,
|
||||
count: 51,
|
||||
numberOfPages: 2);
|
||||
_mockApiHttpClient.GetAsync<PaginatedDto<FavoriteItemDto>>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedPage);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(_getFavoritesRequestFixture.Create(), CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
JsonElement data = jsonDocument.RootElement.GetProperty("data");
|
||||
Assert.Equal(2, data.GetProperty("currentPage").GetInt32());
|
||||
Assert.Equal(50, data.GetProperty("perPage").GetInt32());
|
||||
Assert.Equal(51, data.GetProperty("count").GetInt32());
|
||||
Assert.Equal(2, data.GetProperty("numberOfPages").GetInt32());
|
||||
JsonElement item = Assert.Single(data.GetProperty("data").EnumerateArray());
|
||||
Assert.Equal((int)expectedItem.MediaKind, item.GetProperty("mediaKind").GetInt32());
|
||||
Assert.Equal(expectedItem.MediaItemId, item.GetProperty("mediaItemId").GetGuid());
|
||||
Assert.True(item.GetProperty("isAvailable").GetBoolean());
|
||||
Assert.Equal(expectedItem.LibraryId, item.GetProperty("libraryId").GetGuid());
|
||||
Assert.Equal(expectedItem.Title, item.GetProperty("title").GetString());
|
||||
Assert.Equal(expectedItem.CollectionId, item.GetProperty("collectionId").GetGuid());
|
||||
Assert.Equal(expectedItem.CollectionTitle, item.GetProperty("collectionTitle").GetString());
|
||||
Assert.Equal(expectedItem.CreatorId, item.GetProperty("creatorId").GetGuid());
|
||||
Assert.Equal(expectedItem.CreatorName, item.GetProperty("creatorName").GetString());
|
||||
Assert.Equal(expectedItem.CoverPath, item.GetProperty("coverPath").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenPageAndSizeAreOmitted_ShouldRequestTheDefaultFirstPage()
|
||||
{
|
||||
// Arrange
|
||||
GetFavoritesRequest request = _getFavoritesRequestFixture.Create(includeCurrentPage: false, includePerPage: false, includeMediaKind: false);
|
||||
_mockApiHttpClient.GetAsync<PaginatedDto<FavoriteItemDto>>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedDto<FavoriteItemDto>>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/me/favorites?currentPage=1&perPage=200"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOnlyThePageIsSupplied_ShouldForwardItWithTheDefaultPageSize()
|
||||
{
|
||||
// Arrange
|
||||
GetFavoritesRequest request = _getFavoritesRequestFixture.Create(
|
||||
currentPage: 3,
|
||||
includeMediaKind: false,
|
||||
includePerPage: false);
|
||||
_mockApiHttpClient.GetAsync<PaginatedDto<FavoriteItemDto>>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedDto<FavoriteItemDto>>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/me/favorites?currentPage=3&perPage=200"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOnlyThePageSizeIsSupplied_ShouldForwardItWithTheDefaultFirstPage()
|
||||
{
|
||||
// Arrange
|
||||
GetFavoritesRequest request = _getFavoritesRequestFixture.Create(
|
||||
perPage: 25,
|
||||
includeMediaKind: false,
|
||||
includeCurrentPage: false);
|
||||
_mockApiHttpClient.GetAsync<PaginatedDto<FavoriteItemDto>>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedDto<FavoriteItemDto>>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/me/favorites?currentPage=1&perPage=25"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(2, 50, "users/me/favorites?currentPage=2&perPage=50")] // both the page and the size are supplied
|
||||
[InlineData(-1, 0, "users/me/favorites?currentPage=-1&perPage=0")] // out of range values are preserved, so the API reports its own validation
|
||||
public async Task ExecuteAsync_WhenPaginationValuesAreSupplied_ShouldForwardTheNormalizedQueryString(int currentPage, int perPage, string expectedEndpoint)
|
||||
{
|
||||
// Arrange
|
||||
GetFavoritesRequest request = _getFavoritesRequestFixture.Create(
|
||||
currentPage: currentPage,
|
||||
perPage: perPage,
|
||||
includeMediaKind: false);
|
||||
_mockApiHttpClient.GetAsync<PaginatedDto<FavoriteItemDto>>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedDto<FavoriteItemDto>>(
|
||||
Arg.Is<string>(endpoint => endpoint == expectedEndpoint),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(FavoriteMediaKind.MusicArtist, "users/me/favorites?currentPage=1&perPage=200&mediaKind=MusicArtist")] // artist favorites
|
||||
[InlineData(FavoriteMediaKind.MusicAlbum, "users/me/favorites?currentPage=1&perPage=200&mediaKind=MusicAlbum")] // album favorites
|
||||
[InlineData(FavoriteMediaKind.MusicTrack, "users/me/favorites?currentPage=1&perPage=200&mediaKind=MusicTrack")] // track favorites
|
||||
[InlineData(FavoriteMediaKind.Book, "users/me/favorites?currentPage=1&perPage=200&mediaKind=Book")] // book favorites
|
||||
public async Task ExecuteAsync_WhenMediaKindIsSupplied_ShouldAppendTheCanonicalKindToTheQueryString(FavoriteMediaKind mediaKind, string expectedEndpoint)
|
||||
{
|
||||
// Arrange
|
||||
GetFavoritesRequest request = _getFavoritesRequestFixture.Create(
|
||||
mediaKind: mediaKind,
|
||||
includeCurrentPage: false,
|
||||
includePerPage: false);
|
||||
_mockApiHttpClient.GetAsync<PaginatedDto<FavoriteItemDto>>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedDto<FavoriteItemDto>>(
|
||||
Arg.Is<string>(endpoint => endpoint == expectedEndpoint),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenMediaKindIsOmitted_ShouldNotAppendAMediaKindToTheQueryString()
|
||||
{
|
||||
// Arrange
|
||||
GetFavoritesRequest request = _getFavoritesRequestFixture.Create(
|
||||
includeMediaKind: false,
|
||||
includeCurrentPage: false,
|
||||
includePerPage: false);
|
||||
_mockApiHttpClient.GetAsync<PaginatedDto<FavoriteItemDto>>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedDto<FavoriteItemDto>>(
|
||||
Arg.Is<string>(endpoint => !endpoint.Contains("mediaKind", StringComparison.Ordinal)),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSetPrivateNoStoreAndCookieVaryHeaders()
|
||||
{
|
||||
// Arrange
|
||||
_mockApiHttpClient.GetAsync<PaginatedDto<FavoriteItemDto>>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(_getFavoritesRequestFixture.Create(), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString());
|
||||
Assert.Equal("Cookie", _sut.HttpContext.Response.Headers["Vary"].ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
PaginatedDto<FavoriteItemDto> expectedPage = _paginatedDtoFixture.Create();
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
_mockApiHttpClient.GetAsync<PaginatedDto<FavoriteItemDto>>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.ArgAt<CancellationToken>(1).ThrowIfCancellationRequested();
|
||||
return expectedPage;
|
||||
}, callInfo.ArgAt<CancellationToken>(1)));
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(_getFavoritesRequestFixture.Create(), cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
}
|
||||
+298
@@ -0,0 +1,298 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
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.Favorites.Index;
|
||||
using Lumina.Presentation.Web.Core.Themes;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Antiforgery;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Localization;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Reflection;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Favorites.Index;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="FavoritesIndexViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class FavoritesIndexViewEndpointTests
|
||||
{
|
||||
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 FavoritesIndexViewEndpoint _sut;
|
||||
private readonly ThemePageRenderResultDtoFixture _themePageRenderResultDtoFixture = new();
|
||||
private readonly List<object?> _artistRouteValues = [];
|
||||
private readonly List<object?> _albumRouteValues = [];
|
||||
private readonly List<object?> _trackRouteValues = [];
|
||||
private readonly List<object?> _bookRouteValues = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="FavoritesIndexViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public FavoritesIndexViewEndpointTests()
|
||||
{
|
||||
_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" ? "Favorites" : $"Localized-{callInfo.Arg<string>()}"));
|
||||
_mockStringLocalizer.GetAllStrings(Arg.Any<bool>()).Returns(new LocalizedString[]
|
||||
{
|
||||
new("Title", "Favorites"),
|
||||
new("NoFavorites", "You have no favorites yet.")
|
||||
});
|
||||
_mockStringLocalizerFactory = Substitute.For<IStringLocalizerFactory>();
|
||||
_mockStringLocalizerFactory.Create(Arg.Any<string>(), Arg.Any<string>()).Returns(_mockStringLocalizer);
|
||||
_sut = Factory.Create<FavoritesIndexViewEndpoint>(_mockUrlService, _mockThemePageRenderer, _mockAntiforgery, _mockStringLocalizerFactory);
|
||||
TestHttpContextFactory.ConfigureSession(_sut.HttpContext, TestHttpContextFactory.CreateSession());
|
||||
_sut.HttpContext.Request.Path = "/en-us/favorites";
|
||||
|
||||
StubUrls();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenThemeRenderingSucceeds_ShouldRenderThemedViewWithDocumentedPageData()
|
||||
{
|
||||
// Arrange
|
||||
ThemePageRenderResultDto renderedPage = _themePageRenderResultDtoFixture.Create(
|
||||
content: "<section>favorites</section>",
|
||||
script: "<script>favorites</script>");
|
||||
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(renderedPage));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("/Core/Views/Shared/_ThemedView.cshtml", GetRenderedViewName(result));
|
||||
await _mockThemePageRenderer.Received(1).RenderAsync(
|
||||
Arg.Is<ThemePageDto>(page =>
|
||||
page.PageKey == "favorites/index" &&
|
||||
page.Title == "Favorites" &&
|
||||
page.Description == string.Empty &&
|
||||
string.Equals(page.PageData["getFavoritesUrl"] as string, "http://localhost/en-us/favorites/api-get-favorites", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["getFavoriteStatusUrl"] as string, "http://localhost/en-us/favorites/api-get-favorite-status", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["addFavoriteUrl"] as string, "http://localhost/en-us/favorites/api-add-favorite", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["removeFavoriteUrl"] as string, "http://localhost/en-us/favorites/{mediaKind}/{mediaItemId}/api-remove-favorite", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["artistUrl"] as string, $"http://localhost/en-us/library/audio-library/music-library/artists/{ZERO_GUID}", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["albumUrl"] as string, $"http://localhost/en-us/library/audio-library/music-library/artists/{ZERO_GUID}/albums/{ZERO_GUID}", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["trackUrl"] as string, $"http://localhost/en-us/library/audio-library/music-library/artists/{ZERO_GUID}/albums/{ZERO_GUID}/tracks/{ZERO_GUID}", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["bookUrl"] as string, $"http://localhost/en-us/library/written-content-library/books-library/books/{ZERO_GUID}", StringComparison.Ordinal) &&
|
||||
HasDocumentedLocalizedStrings(page)),
|
||||
Arg.Is<string?>(requestedThemeId => requestedThemeId == null),
|
||||
Arg.Any<CancellationToken>());
|
||||
_mockAntiforgery.Received(1).GetAndStoreTokens(_sut.HttpContext);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldUseTheAllZeroGuidTemplatesOfTheMediaItemRoutes()
|
||||
{
|
||||
// Arrange
|
||||
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_themePageRenderResultDtoFixture.Create()));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// The detail pages replace each all-zero Guid placeholder one at a time, so the route values must be empty Guids in route order.
|
||||
Assert.Single(_artistRouteValues);
|
||||
AssertRouteValueIsEmptyGuid(_artistRouteValues[0], "artistId");
|
||||
Assert.Single(_albumRouteValues);
|
||||
AssertRouteValueIsEmptyGuid(_albumRouteValues[0], "artistId");
|
||||
AssertRouteValueIsEmptyGuid(_albumRouteValues[0], "albumId");
|
||||
Assert.Single(_trackRouteValues);
|
||||
AssertRouteValueIsEmptyGuid(_trackRouteValues[0], "artistId");
|
||||
AssertRouteValueIsEmptyGuid(_trackRouteValues[0], "albumId");
|
||||
AssertRouteValueIsEmptyGuid(_trackRouteValues[0], "trackId");
|
||||
Assert.Single(_bookRouteValues);
|
||||
AssertRouteValueIsEmptyGuid(_bookRouteValues[0], "bookId");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSetPrivateNoStoreAndCookieVaryHeaders()
|
||||
{
|
||||
// Arrange
|
||||
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_themePageRenderResultDtoFixture.Create()));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString());
|
||||
Assert.Equal("Cookie", _sut.HttpContext.Response.Headers["Vary"].ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldRequestAndExposeAFreshAntiforgeryToken()
|
||||
{
|
||||
// Arrange
|
||||
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_themePageRenderResultDtoFixture.Create()));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
_mockAntiforgery.Received(1).GetAndStoreTokens(_sut.HttpContext);
|
||||
await _mockThemePageRenderer.Received(1).RenderAsync(
|
||||
Arg.Is<ThemePageDto>(page => string.Equals(page.PageData["antiforgeryToken"] as string, "request-token", StringComparison.Ordinal)),
|
||||
Arg.Any<string?>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenThemeRenderingFails_ShouldFallBackToTheRazorViewWithTheLocalizedTitle()
|
||||
{
|
||||
// Arrange
|
||||
_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(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("/Core/Views/Favorites/Index.cshtml", GetRenderedViewName(result));
|
||||
IReadOnlyDictionary<string, object?> viewData = GetRenderedViewData(result);
|
||||
Assert.Equal("Favorites", viewData["Title"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
ThemePageRenderResultDto renderedPage = _themePageRenderResultDtoFixture.Create();
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.ArgAt<CancellationToken>(2).ThrowIfCancellationRequested();
|
||||
return Result.From(renderedPage);
|
||||
}, callInfo.ArgAt<CancellationToken>(2)));
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(EmptyRequest.Instance, cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the absolute URLs that the endpoint resolves for the favorites page.
|
||||
/// </summary>
|
||||
private void StubUrls()
|
||||
{
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Favorites.GET_FAVORITES).Returns("http://localhost/en-us/favorites/api-get-favorites");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Favorites.GET_FAVORITE_STATUS).Returns("http://localhost/en-us/favorites/api-get-favorite-status");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Favorites.ADD_FAVORITE).Returns("http://localhost/en-us/favorites/api-add-favorite");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Favorites.REMOVE_FAVORITE).Returns("http://localhost/en-us/favorites/{mediaKind}/{mediaItemId}/api-remove-favorite");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Music.ARTIST, Arg.Any<object?>())
|
||||
.Returns(callInfo =>
|
||||
{
|
||||
_artistRouteValues.Add(callInfo.ArgAt<object?>(1));
|
||||
return $"http://localhost/en-us/library/audio-library/music-library/artists/{ZERO_GUID}";
|
||||
});
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Music.ALBUM, Arg.Any<object?>())
|
||||
.Returns(callInfo =>
|
||||
{
|
||||
_albumRouteValues.Add(callInfo.ArgAt<object?>(1));
|
||||
return $"http://localhost/en-us/library/audio-library/music-library/artists/{ZERO_GUID}/albums/{ZERO_GUID}";
|
||||
});
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Music.TRACK, Arg.Any<object?>())
|
||||
.Returns(callInfo =>
|
||||
{
|
||||
_trackRouteValues.Add(callInfo.ArgAt<object?>(1));
|
||||
return $"http://localhost/en-us/library/audio-library/music-library/artists/{ZERO_GUID}/albums/{ZERO_GUID}/tracks/{ZERO_GUID}";
|
||||
});
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Books.EDIT_BOOK, Arg.Any<object?>())
|
||||
.Returns(callInfo =>
|
||||
{
|
||||
_bookRouteValues.Add(callInfo.ArgAt<object?>(1));
|
||||
return $"http://localhost/en-us/library/written-content-library/books-library/books/{ZERO_GUID}";
|
||||
});
|
||||
}
|
||||
|
||||
/// <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 view data 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 view data entries passed to the rendered view.</returns>
|
||||
private static IReadOnlyDictionary<string, object?> GetRenderedViewData(IResult result)
|
||||
{
|
||||
RazorViewResult viewResult = Assert.IsType<RazorViewResult>(result);
|
||||
FieldInfo? viewDataField = typeof(RazorViewResult).GetField("_viewData", BindingFlags.Instance | BindingFlags.NonPublic);
|
||||
Assert.NotNull(viewDataField);
|
||||
return (IReadOnlyDictionary<string, object?>)viewDataField.GetValue(viewResult)!;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the page data carries the localized strings of the favorites page.
|
||||
/// </summary>
|
||||
/// <param name="page">The page model passed to the theme renderer.</param>
|
||||
/// <returns><see langword="true"/> when the localized strings are exposed under the <c>strings</c> key; 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;
|
||||
return string.Equals(strings["Title"] as string, "Favorites", StringComparison.Ordinal)
|
||||
&& string.Equals(strings["NoFavorites"] as string, "You have no favorites yet.", 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)!);
|
||||
}
|
||||
}
|
||||
+184
@@ -0,0 +1,184 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Favorites.RemoveFavorite;
|
||||
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.Favorites.RemoveFavorite;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="RemoveFavoriteEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RemoveFavoriteEndpointTests
|
||||
{
|
||||
private const string ZERO_GUID = "00000000-0000-0000-0000-000000000000";
|
||||
|
||||
private static readonly Guid s_mediaItemId = Guid.Parse("22222222-2222-2222-2222-222222222222");
|
||||
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly RemoveFavoriteEndpoint _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RemoveFavoriteEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public RemoveFavoriteEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<RemoveFavoriteEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiSucceeds_ShouldReturnSuccessJsonWithoutPayload()
|
||||
{
|
||||
// Arrange
|
||||
SetRouteValues("MusicTrack", s_mediaItemId.ToString());
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.False(jsonDocument.RootElement.TryGetProperty("data", out JsonElement _));
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
Arg.Is<string>(endpoint => endpoint == $"users/me/favorites/MusicTrack/{s_mediaItemId}"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("MusicArtist", "MusicArtist")] // canonical member name
|
||||
[InlineData("MusicAlbum", "MusicAlbum")] // another canonical member name
|
||||
[InlineData("MusicTrack", "MusicTrack")] // another canonical member name
|
||||
[InlineData("Book", "Book")] // another canonical member name
|
||||
[InlineData("musictrack", "MusicTrack")] // lowercase member name
|
||||
[InlineData("MUSICTRACK", "MusicTrack")] // uppercase member name
|
||||
[InlineData("musicTrack", "MusicTrack")] // mixed case member name
|
||||
public async Task ExecuteAsync_WhenMediaKindNameIsValid_ShouldForwardTheCanonicalMemberName(string routeMediaKind, string expectedMediaKind)
|
||||
{
|
||||
// Arrange
|
||||
SetRouteValues(routeMediaKind, s_mediaItemId.ToString());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
Arg.Is<string>(endpoint => endpoint == $"users/me/favorites/{expectedMediaKind}/{s_mediaItemId}"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("1")] // numeric enum value
|
||||
[InlineData("0")] // numeric enum value
|
||||
[InlineData("NotAFavoriteMediaKind")] // undefined member name
|
||||
[InlineData("None")] // the default value is not a kind that can be favorited
|
||||
[InlineData("none")] // the default value, matched case insensitively
|
||||
[InlineData("MusicTrack,Book")] // comma separated member names
|
||||
[InlineData("Music Track")] // member name with a space
|
||||
[InlineData("MusicTrack/../..")] // path traversal attempt
|
||||
[InlineData("..")] // dot segment
|
||||
[InlineData("MusicTrack%2F..")] // encoded slash traversal attempt
|
||||
public async Task ExecuteAsync_WhenMediaKindNameIsRejected_ShouldForwardTheInvalidPlaceholder(string routeMediaKind)
|
||||
{
|
||||
// Arrange
|
||||
SetRouteValues(routeMediaKind, s_mediaItemId.ToString());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
Arg.Is<string>(endpoint => endpoint == $"users/me/favorites/Invalid/{s_mediaItemId}"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenMediaItemIdIsAnUppercaseGuid_ShouldForwardItLowercase()
|
||||
{
|
||||
// Arrange
|
||||
string uppercaseMediaItemId = s_mediaItemId.ToString().ToUpperInvariant();
|
||||
SetRouteValues("MusicTrack", uppercaseMediaItemId);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
Arg.Is<string>(endpoint => endpoint == $"users/me/favorites/MusicTrack/{s_mediaItemId}"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenMediaItemIdIsNotAGuid_ShouldForwardTheEmptyGuid()
|
||||
{
|
||||
// Arrange
|
||||
SetRouteValues("MusicTrack", "not-a-guid");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
Arg.Is<string>(endpoint => endpoint == $"users/me/favorites/MusicTrack/{ZERO_GUID}"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldForwardTheInvalidPlaceholderAndTheEmptyGuid()
|
||||
{
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
Arg.Is<string>(endpoint => endpoint == $"users/me/favorites/Invalid/{ZERO_GUID}"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
SetRouteValues("MusicTrack", s_mediaItemId.ToString());
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
_mockApiHttpClient.DeleteAsync(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.ArgAt<CancellationToken>(1).ThrowIfCancellationRequested();
|
||||
}, callInfo.ArgAt<CancellationToken>(1)));
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(EmptyRequest.Instance, cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the route values of the endpoint under test.
|
||||
/// </summary>
|
||||
/// <param name="mediaKind">The value of the media kind route segment.</param>
|
||||
/// <param name="mediaItemId">The value of the media item identifier route segment.</param>
|
||||
private void SetRouteValues(object mediaKind, object mediaItemId)
|
||||
{
|
||||
_sut.HttpContext.Request.RouteValues["mediaKind"] = mediaKind;
|
||||
_sut.HttpContext.Request.RouteValues["mediaItemId"] = mediaItemId;
|
||||
}
|
||||
}
|
||||
+320
@@ -0,0 +1,320 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Common.DTO.Playlists;
|
||||
using Lumina.Presentation.Web.Common.Enums.Playlists;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Playlists.GetPlaylist;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Playlists;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Playlists;
|
||||
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.Text.Json.Serialization;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Playlists.GetPlaylist;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetPlaylistEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetPlaylistEndpointTests
|
||||
{
|
||||
private const string ZERO_GUID = "00000000-0000-0000-0000-000000000000";
|
||||
|
||||
private static readonly Guid s_playlistId = Guid.Parse("ABCDEFAB-CDEF-ABCD-EFAB-CDEFABCDEFAB");
|
||||
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly GetPlaylistEndpoint _sut;
|
||||
private readonly GetPlaylistRequestFixture _getPlaylistRequestFixture = new();
|
||||
private readonly PlaylistDtoFixture _playlistDtoFixture = new();
|
||||
private readonly PlaylistEntryDtoFixture _playlistEntryDtoFixture = new();
|
||||
private readonly PaginatedDtoFixture<PlaylistEntryDto> _paginatedDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPlaylistEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetPlaylistEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<GetPlaylistEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiSucceeds_ShouldReturnSuccessJsonWithPlaylistAndPaginationMetadata()
|
||||
{
|
||||
// Arrange
|
||||
PlaylistEntryDto expectedEntry = _playlistEntryDtoFixture.Create(
|
||||
position: 0,
|
||||
mediaItemTitle: "First track",
|
||||
mediaItemType: PlaylistMediaItemType.MusicTrack);
|
||||
PlaylistDto expectedPlaylist = _playlistDtoFixture.Create(
|
||||
entries: _paginatedDtoFixture.Create(
|
||||
data: [expectedEntry],
|
||||
currentPage: 2,
|
||||
perPage: 10,
|
||||
count: 42,
|
||||
numberOfPages: 5));
|
||||
SetRoutePlaylistId(s_playlistId);
|
||||
_mockApiHttpClient.GetAsync<PlaylistDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedPlaylist);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(_getPlaylistRequestFixture.Create(), CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
JsonSerializerOptions jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter() }
|
||||
};
|
||||
PlaylistDto actualPlaylist = JsonSerializer.Deserialize<PlaylistDto>(
|
||||
jsonDocument.RootElement.GetProperty("data").GetRawText(),
|
||||
jsonOptions)!;
|
||||
Assert.Equal(expectedPlaylist.Id, actualPlaylist.Id);
|
||||
Assert.Equal(expectedPlaylist.Name, actualPlaylist.Name);
|
||||
Assert.Equal(expectedPlaylist.Description, actualPlaylist.Description);
|
||||
Assert.Equal(expectedPlaylist.Type, actualPlaylist.Type);
|
||||
Assert.Equal(expectedPlaylist.CreatedOnUtc, actualPlaylist.CreatedOnUtc);
|
||||
Assert.Equal(expectedPlaylist.UpdatedOnUtc, actualPlaylist.UpdatedOnUtc);
|
||||
Assert.Equal(expectedPlaylist.Entries.CurrentPage, actualPlaylist.Entries.CurrentPage);
|
||||
Assert.Equal(expectedPlaylist.Entries.PerPage, actualPlaylist.Entries.PerPage);
|
||||
Assert.Equal(expectedPlaylist.Entries.Count, actualPlaylist.Entries.Count);
|
||||
Assert.Equal(expectedPlaylist.Entries.NumberOfPages, actualPlaylist.Entries.NumberOfPages);
|
||||
PlaylistEntryDto actualEntry = Assert.Single(actualPlaylist.Entries.Data);
|
||||
Assert.Equal(expectedEntry.Id, actualEntry.Id);
|
||||
Assert.Equal(expectedEntry.MediaItemId, actualEntry.MediaItemId);
|
||||
Assert.Equal(expectedEntry.MediaItemType, actualEntry.MediaItemType);
|
||||
Assert.Equal(expectedEntry.Position, actualEntry.Position);
|
||||
Assert.Equal(expectedEntry.MediaItemTitle, actualEntry.MediaItemTitle);
|
||||
Assert.Equal(expectedEntry.CollectionTitle, actualEntry.CollectionTitle);
|
||||
Assert.Equal(expectedEntry.CreatorName, actualEntry.CreatorName);
|
||||
Assert.Equal(expectedEntry.DurationInSeconds, actualEntry.DurationInSeconds);
|
||||
Assert.Equal(expectedEntry.CoverPath, actualEntry.CoverPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenBothPageParametersAreMissing_ShouldRequestTheFirstPageWithTheDefaultSize()
|
||||
{
|
||||
// Arrange
|
||||
SetRoutePlaylistId(s_playlistId);
|
||||
_mockApiHttpClient.GetAsync<PlaylistDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_playlistDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(
|
||||
_getPlaylistRequestFixture.Create(includeCurrentPage: false, includePerPage: false),
|
||||
CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PlaylistDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == $"users/me/playlists/{s_playlistId}?currentPage=1&perPage=200"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOnlyCurrentPageIsProvided_ShouldUseTheProvidedPageAndTheDefaultSize()
|
||||
{
|
||||
// Arrange
|
||||
SetRoutePlaylistId(s_playlistId);
|
||||
_mockApiHttpClient.GetAsync<PlaylistDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_playlistDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(
|
||||
_getPlaylistRequestFixture.Create(currentPage: 3, includePerPage: false),
|
||||
CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PlaylistDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == $"users/me/playlists/{s_playlistId}?currentPage=3&perPage=200"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOnlyPerPageIsProvided_ShouldUseTheFirstPageAndTheProvidedSize()
|
||||
{
|
||||
// Arrange
|
||||
SetRoutePlaylistId(s_playlistId);
|
||||
_mockApiHttpClient.GetAsync<PlaylistDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_playlistDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(
|
||||
_getPlaylistRequestFixture.Create(perPage: 50, includeCurrentPage: false),
|
||||
CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PlaylistDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == $"users/me/playlists/{s_playlistId}?currentPage=1&perPage=50"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenBothPageParametersAreProvided_ShouldPreserveBoth()
|
||||
{
|
||||
// Arrange
|
||||
SetRoutePlaylistId(s_playlistId);
|
||||
_mockApiHttpClient.GetAsync<PlaylistDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_playlistDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(
|
||||
_getPlaylistRequestFixture.Create(currentPage: 4, perPage: 25),
|
||||
CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PlaylistDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == $"users/me/playlists/{s_playlistId}?currentPage=4&perPage=25"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenPlaylistIdIsAnUppercaseGuid_ShouldForwardItInLowercase()
|
||||
{
|
||||
// Arrange
|
||||
SetRoutePlaylistId(s_playlistId.ToString().ToUpperInvariant());
|
||||
_mockApiHttpClient.GetAsync<PlaylistDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_playlistDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(
|
||||
_getPlaylistRequestFixture.Create(includeCurrentPage: false, includePerPage: false),
|
||||
CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PlaylistDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == $"users/me/playlists/{s_playlistId}?currentPage=1&perPage=200"),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockApiHttpClient.DidNotReceive().GetAsync<PlaylistDto>(
|
||||
Arg.Is<string>(endpoint => endpoint.Contains(s_playlistId.ToString().ToUpperInvariant(), StringComparison.Ordinal)),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenPlaylistIdIsNotAGuid_ShouldForwardTheEmptyGuid()
|
||||
{
|
||||
// Arrange
|
||||
SetRoutePlaylistId("not-a-guid");
|
||||
_mockApiHttpClient.GetAsync<PlaylistDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_playlistDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(
|
||||
_getPlaylistRequestFixture.Create(includeCurrentPage: false, includePerPage: false),
|
||||
CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PlaylistDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == $"users/me/playlists/{ZERO_GUID}?currentPage=1&perPage=200"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenPlaylistIdRouteValueIsMissing_ShouldForwardTheEmptyGuid()
|
||||
{
|
||||
// Arrange
|
||||
_mockApiHttpClient.GetAsync<PlaylistDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_playlistDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(
|
||||
_getPlaylistRequestFixture.Create(includeCurrentPage: false, includePerPage: false),
|
||||
CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PlaylistDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == $"users/me/playlists/{ZERO_GUID}?currentPage=1&perPage=200"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // basic SQL injection
|
||||
[InlineData("1;DROP TABLE")] // destructive injection
|
||||
[InlineData("../../admin")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // markup injection
|
||||
[InlineData("𝕡𝕝𝕒𝕪𝕝𝕚𝕤𝕥")] // unicode payload
|
||||
public async Task ExecuteAsync_WhenPlaylistIdIsCrafted_ShouldNormalizeItAndNeverForwardTheRawValue(string payload)
|
||||
{
|
||||
// Arrange
|
||||
SetRoutePlaylistId(payload);
|
||||
_mockApiHttpClient.GetAsync<PlaylistDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_playlistDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(
|
||||
_getPlaylistRequestFixture.Create(includeCurrentPage: false, includePerPage: false),
|
||||
CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PlaylistDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == $"users/me/playlists/{ZERO_GUID}?currentPage=1&perPage=200"),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockApiHttpClient.DidNotReceive().GetAsync<PlaylistDto>(
|
||||
Arg.Is<string>(endpoint => endpoint.Contains(payload, StringComparison.Ordinal)),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSetPrivateNoStoreAndCookieVaryHeaders()
|
||||
{
|
||||
// Arrange
|
||||
SetRoutePlaylistId(s_playlistId);
|
||||
_mockApiHttpClient.GetAsync<PlaylistDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_playlistDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(_getPlaylistRequestFixture.Create(), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString());
|
||||
Assert.Equal("Cookie", _sut.HttpContext.Response.Headers["Vary"].ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
PlaylistDto expectedPlaylist = _playlistDtoFixture.Create();
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
SetRoutePlaylistId(s_playlistId);
|
||||
_mockApiHttpClient.GetAsync<PlaylistDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.ArgAt<CancellationToken>(1).ThrowIfCancellationRequested();
|
||||
return expectedPlaylist;
|
||||
}, callInfo.ArgAt<CancellationToken>(1)));
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(_getPlaylistRequestFixture.Create(), cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the route value of the playlist identifier route segment.
|
||||
/// </summary>
|
||||
/// <param name="playlistId">The value of the playlist identifier route segment.</param>
|
||||
private void SetRoutePlaylistId(object playlistId)
|
||||
{
|
||||
_sut.HttpContext.Request.RouteValues["playlistId"] = playlistId;
|
||||
}
|
||||
}
|
||||
+352
@@ -0,0 +1,352 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.Playlists;
|
||||
using Lumina.Presentation.Web.Common.DTO.Themes;
|
||||
using Lumina.Presentation.Web.Common.Enums.Playlists;
|
||||
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.Playlists.Item;
|
||||
using Lumina.Presentation.Web.Core.Themes;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Antiforgery;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
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.Playlists.Item;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="AddPlaylistViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddPlaylistViewEndpointTests
|
||||
{
|
||||
private const string ZERO_GUID = "00000000-0000-0000-0000-000000000000";
|
||||
private const string CREATE_PLAYLIST_TITLE = "Create playlist";
|
||||
|
||||
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 AddPlaylistViewEndpoint _sut;
|
||||
private readonly ThemePageRenderResultDtoFixture _themePageRenderResultDtoFixture = new();
|
||||
private readonly List<object?> _itemRouteValues = [];
|
||||
private readonly List<object?> _artistAlbumsRouteValues = [];
|
||||
private readonly List<object?> _albumTracksRouteValues = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddPlaylistViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public AddPlaylistViewEndpointTests()
|
||||
{
|
||||
_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>() == "CreatePlaylist" ? CREATE_PLAYLIST_TITLE : $"Localized-{callInfo.Arg<string>()}"));
|
||||
_mockStringLocalizer.GetAllStrings(Arg.Any<bool>()).Returns(new LocalizedString[]
|
||||
{
|
||||
new("CreatePlaylist", CREATE_PLAYLIST_TITLE),
|
||||
new("Cancel", "Cancel")
|
||||
});
|
||||
_mockStringLocalizerFactory = Substitute.For<IStringLocalizerFactory>();
|
||||
_mockStringLocalizerFactory.Create(Arg.Any<string>(), Arg.Any<string>()).Returns(_mockStringLocalizer);
|
||||
_sut = Factory.Create<AddPlaylistViewEndpoint>(_mockUrlService, _mockThemePageRenderer, _mockAntiforgery, _mockStringLocalizerFactory);
|
||||
TestHttpContextFactory.ConfigureSession(_sut.HttpContext, TestHttpContextFactory.CreateSession());
|
||||
_sut.HttpContext.Request.Path = "/en-us/playlists/item";
|
||||
|
||||
StubUrls();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenThemeRenderingSucceeds_ShouldRenderThemedPageWithCreatePageMetadata()
|
||||
{
|
||||
// Arrange
|
||||
ThemePageRenderResultDto renderedPage = _themePageRenderResultDtoFixture.Create(
|
||||
content: "<section>create playlist</section>",
|
||||
script: "<script>create playlist</script>");
|
||||
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(renderedPage));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("/Core/Views/Shared/_ThemedView.cshtml", GetRenderedViewName(result));
|
||||
ThemeViewDto themedView = Assert.IsType<ThemeViewDto>(GetRenderedModel(result));
|
||||
Assert.Equal(renderedPage.Content, themedView.Content);
|
||||
await _mockThemePageRenderer.Received(1).RenderAsync(
|
||||
Arg.Is<ThemePageDto>(page =>
|
||||
page.PageKey == "playlists/item" &&
|
||||
page.Title == CREATE_PLAYLIST_TITLE &&
|
||||
page.Description == string.Empty &&
|
||||
Equals(page.PageData["isNew"], true) &&
|
||||
string.Equals(page.PageData["playlistId"] as string, Guid.Empty.ToString(), StringComparison.Ordinal) &&
|
||||
Equals(page.PageData["entriesPerPage"], 200) &&
|
||||
HasEmptyPlaylistJson(page)),
|
||||
Arg.Is<string?>(requestedThemeId => requestedThemeId == null),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenThemeRenderingSucceeds_ShouldExposeEveryPageDataUrl()
|
||||
{
|
||||
// Arrange
|
||||
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_themePageRenderResultDtoFixture.Create()));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockThemePageRenderer.Received(1).RenderAsync(
|
||||
Arg.Is<ThemePageDto>(page =>
|
||||
string.Equals(page.PageData["createPlaylistUrl"] as string, "http://localhost/en-us/playlists/api-create-playlist", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["itemUrl"] as string, $"http://localhost/en-us/playlists/item/{ZERO_GUID}", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["getEnabledLibrariesUrl"] as string, "http://localhost/en-us/libraries/manage/api-get-enabled-libraries", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["getArtistsUrl"] as string, "http://localhost/en-us/library/audio-library/music-library/artists/api-get-artists", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["getArtistAlbumsUrl"] as string, $"http://localhost/en-us/library/audio-library/music-library/artists/{ZERO_GUID}/albums/api-get-albums", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["getAlbumTracksUrl"] as string, $"http://localhost/en-us/library/audio-library/music-library/artists/{ZERO_GUID}/albums/{ZERO_GUID}/tracks/api-get-tracks", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["indexUrl"] as string, "http://localhost/en-us/playlists", StringComparison.Ordinal)),
|
||||
Arg.Any<string?>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldUseTheAllZeroGuidTemplatesOfTheMediaItemRoutes()
|
||||
{
|
||||
// Arrange
|
||||
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_themePageRenderResultDtoFixture.Create()));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// The page script replaces each all-zero Guid placeholder one at a time, so the route values must be empty Guids in route order.
|
||||
object? itemRouteValues = Assert.Single(_itemRouteValues);
|
||||
AssertRouteValueIsEmptyGuid(itemRouteValues, "playlistId");
|
||||
object? artistAlbumsRouteValues = Assert.Single(_artistAlbumsRouteValues);
|
||||
AssertRouteValueIsEmptyGuid(artistAlbumsRouteValues, "artistId");
|
||||
object? albumTracksRouteValues = Assert.Single(_albumTracksRouteValues);
|
||||
AssertRouteValueIsEmptyGuid(albumTracksRouteValues, "artistId");
|
||||
AssertRouteValueIsEmptyGuid(albumTracksRouteValues, "albumId");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenThemeRenderingSucceeds_ShouldExposeTheAntiforgeryTokenAndTheLocalizedStrings()
|
||||
{
|
||||
// Arrange
|
||||
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_themePageRenderResultDtoFixture.Create()));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.IsType<RazorViewResult>(result);
|
||||
_mockAntiforgery.Received(1).GetAndStoreTokens(_sut.HttpContext);
|
||||
await _mockThemePageRenderer.Received(1).RenderAsync(
|
||||
Arg.Is<ThemePageDto>(page =>
|
||||
string.Equals(page.PageData["antiforgeryToken"] as string, "request-token", StringComparison.Ordinal) &&
|
||||
HasDocumentedLocalizedStrings(page)),
|
||||
Arg.Any<string?>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSetPrivateNoStoreAndCookieVaryHeaders()
|
||||
{
|
||||
// Arrange
|
||||
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_themePageRenderResultDtoFixture.Create()));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString());
|
||||
Assert.Equal("Cookie", _sut.HttpContext.Response.Headers["Vary"].ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenThemeRenderingFails_ShouldFallBackToTheRazorViewWithTheEmptyPlaylist()
|
||||
{
|
||||
// Arrange
|
||||
_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(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("/Core/Views/Playlists/Item.cshtml", GetRenderedViewName(result));
|
||||
IReadOnlyDictionary<string, object?> viewData = GetRenderedViewData(result);
|
||||
Assert.Equal(CREATE_PLAYLIST_TITLE, viewData["Title"]);
|
||||
Assert.True((bool)viewData["IsNew"]!);
|
||||
PlaylistDto playlist = Assert.IsType<PlaylistDto>(GetRenderedModel(result));
|
||||
Assert.Equal(Guid.Empty, playlist.Id);
|
||||
Assert.Equal(string.Empty, playlist.Name);
|
||||
Assert.Null(playlist.Description);
|
||||
Assert.Equal(PlaylistType.Music, playlist.Type);
|
||||
Assert.Empty(playlist.Entries.Data);
|
||||
Assert.Equal(1, playlist.Entries.CurrentPage);
|
||||
Assert.Equal(200, playlist.Entries.PerPage);
|
||||
Assert.Equal(0, playlist.Entries.Count);
|
||||
Assert.Equal(0, playlist.Entries.NumberOfPages);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldNotCallTheApi()
|
||||
{
|
||||
// Arrange
|
||||
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_themePageRenderResultDtoFixture.Create()));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Empty(_mockApiHttpClient.ReceivedCalls());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the absolute URLs that the endpoint resolves for the create playlist page, capturing the route values of the templated routes.
|
||||
/// </summary>
|
||||
private void StubUrls()
|
||||
{
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Playlists.CREATE_PLAYLIST)
|
||||
.Returns("http://localhost/en-us/playlists/api-create-playlist");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Playlists.ITEM, Arg.Any<object?>())
|
||||
.Returns(callInfo =>
|
||||
{
|
||||
_itemRouteValues.Add(callInfo.ArgAt<object?>(1));
|
||||
return $"http://localhost/en-us/playlists/item/{ZERO_GUID}";
|
||||
});
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.GET_ENABLED_LIBRARIES)
|
||||
.Returns("http://localhost/en-us/libraries/manage/api-get-enabled-libraries");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Music.GET_ARTISTS)
|
||||
.Returns("http://localhost/en-us/library/audio-library/music-library/artists/api-get-artists");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Music.GET_ARTIST_ALBUMS, Arg.Any<object?>())
|
||||
.Returns(callInfo =>
|
||||
{
|
||||
_artistAlbumsRouteValues.Add(callInfo.ArgAt<object?>(1));
|
||||
return $"http://localhost/en-us/library/audio-library/music-library/artists/{ZERO_GUID}/albums/api-get-albums";
|
||||
});
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Music.GET_ALBUM_TRACKS, Arg.Any<object?>())
|
||||
.Returns(callInfo =>
|
||||
{
|
||||
_albumTracksRouteValues.Add(callInfo.ArgAt<object?>(1));
|
||||
return $"http://localhost/en-us/library/audio-library/music-library/artists/{ZERO_GUID}/albums/{ZERO_GUID}/tracks/api-get-tracks";
|
||||
});
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Playlists.INDEX)
|
||||
.Returns("http://localhost/en-us/playlists");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the serialized playlist of the page is the empty playlist the create page expects.
|
||||
/// </summary>
|
||||
/// <param name="page">The page model passed to the theme renderer.</param>
|
||||
/// <returns><see langword="true"/> when the serialized playlist is empty and carries the default pagination shape; otherwise <see langword="false"/>.</returns>
|
||||
private static bool HasEmptyPlaylistJson(ThemePageDto page)
|
||||
{
|
||||
if (!page.PageData.TryGetValue("playlistJson", out object? value) || value is not string playlistJson)
|
||||
return false;
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(playlistJson);
|
||||
JsonElement root = jsonDocument.RootElement;
|
||||
JsonElement entries = root.GetProperty("entries");
|
||||
return root.GetProperty("id").GetGuid() == Guid.Empty
|
||||
&& string.Equals(root.GetProperty("name").GetString(), string.Empty, StringComparison.Ordinal)
|
||||
&& root.GetProperty("description").ValueKind == JsonValueKind.Null
|
||||
&& string.Equals(root.GetProperty("type").GetString(), nameof(PlaylistType.Music), StringComparison.Ordinal)
|
||||
&& entries.GetProperty("currentPage").GetInt32() == 1
|
||||
&& entries.GetProperty("perPage").GetInt32() == 200
|
||||
&& entries.GetProperty("count").GetInt32() == 0
|
||||
&& entries.GetProperty("numberOfPages").GetInt32() == 0
|
||||
&& entries.GetProperty("data").GetArrayLength() == 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the page data carries the localized strings of the playlist page.
|
||||
/// </summary>
|
||||
/// <param name="page">The page model passed to the theme renderer.</param>
|
||||
/// <returns><see langword="true"/> when the localized strings are exposed under the <c>strings</c> key; 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;
|
||||
return string.Equals(strings["CreatePlaylist"] as string, CREATE_PLAYLIST_TITLE, StringComparison.Ordinal)
|
||||
&& string.Equals(strings["Cancel"] as string, "Cancel", 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)!);
|
||||
}
|
||||
|
||||
/// <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>
|
||||
/// Reads the private view data 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 view data entries passed to the rendered view.</returns>
|
||||
private static IReadOnlyDictionary<string, object?> GetRenderedViewData(IResult result)
|
||||
{
|
||||
RazorViewResult viewResult = Assert.IsType<RazorViewResult>(result);
|
||||
FieldInfo? viewDataField = typeof(RazorViewResult).GetField("_viewData", BindingFlags.Instance | BindingFlags.NonPublic);
|
||||
Assert.NotNull(viewDataField);
|
||||
return (IReadOnlyDictionary<string, object?>)viewDataField.GetValue(viewResult)!;
|
||||
}
|
||||
}
|
||||
+531
@@ -0,0 +1,531 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.Playlists;
|
||||
using Lumina.Presentation.Web.Common.DTO.Themes;
|
||||
using Lumina.Presentation.Web.Common.Enums.Playlists;
|
||||
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.Playlists.Item;
|
||||
using Lumina.Presentation.Web.Core.Themes;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Playlists;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Antiforgery;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
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.Playlists.Item;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="PlaylistItemViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PlaylistItemViewEndpointTests
|
||||
{
|
||||
private const string ZERO_GUID = "00000000-0000-0000-0000-000000000000";
|
||||
|
||||
private static readonly Guid s_playlistId = Guid.Parse("ABCDEFAB-CDEF-ABCD-EFAB-CDEFABCDEFAB");
|
||||
|
||||
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 PlaylistItemViewEndpoint _sut;
|
||||
private readonly PlaylistDtoFixture _playlistDtoFixture = new();
|
||||
private readonly PlaylistEntryDtoFixture _playlistEntryDtoFixture = new();
|
||||
private readonly PaginatedDtoFixture<PlaylistEntryDto> _paginatedDtoFixture = new();
|
||||
private readonly ThemePageRenderResultDtoFixture _themePageRenderResultDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="PlaylistItemViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public PlaylistItemViewEndpointTests()
|
||||
{
|
||||
_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>(),
|
||||
$"Localized-{callInfo.Arg<string>()}"));
|
||||
_mockStringLocalizer.GetAllStrings(Arg.Any<bool>()).Returns(new LocalizedString[]
|
||||
{
|
||||
new("Save", "Save"),
|
||||
new("Delete", "Delete")
|
||||
});
|
||||
_mockStringLocalizerFactory = Substitute.For<IStringLocalizerFactory>();
|
||||
_mockStringLocalizerFactory.Create(Arg.Any<string>(), Arg.Any<string>()).Returns(_mockStringLocalizer);
|
||||
_sut = Factory.Create<PlaylistItemViewEndpoint>(_mockApiHttpClient, _mockUrlService, _mockThemePageRenderer, _mockAntiforgery, _mockStringLocalizerFactory);
|
||||
TestHttpContextFactory.ConfigureSession(_sut.HttpContext, TestHttpContextFactory.CreateSession());
|
||||
_sut.HttpContext.Request.Path = $"/en-us/playlists/item/{s_playlistId}";
|
||||
|
||||
StubUrls();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenPlaylistIsReturned_ShouldRenderThemedPageWithPlaylistMetadata()
|
||||
{
|
||||
// Arrange
|
||||
PlaylistEntryDto expectedEntry = _playlistEntryDtoFixture.Create(
|
||||
position: 0,
|
||||
mediaItemTitle: "First track",
|
||||
mediaItemType: PlaylistMediaItemType.MusicTrack);
|
||||
PlaylistDto expectedPlaylist = _playlistDtoFixture.Create(
|
||||
name: "Evening listening",
|
||||
description: "Quiet tracks for the end of the day.",
|
||||
entries: _paginatedDtoFixture.Create(
|
||||
data: [expectedEntry],
|
||||
currentPage: 1,
|
||||
perPage: 200,
|
||||
count: 1,
|
||||
numberOfPages: 1));
|
||||
SetRoutePlaylistId(expectedPlaylist.Id);
|
||||
_mockApiHttpClient.GetAsync<PlaylistDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedPlaylist);
|
||||
ThemePageRenderResultDto renderedPage = _themePageRenderResultDtoFixture.Create(
|
||||
content: "<section>playlist</section>",
|
||||
script: "<script>playlist</script>");
|
||||
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(renderedPage));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("/Core/Views/Shared/_ThemedView.cshtml", GetRenderedViewName(result));
|
||||
ThemeViewDto themedView = Assert.IsType<ThemeViewDto>(GetRenderedModel(result));
|
||||
Assert.Equal(renderedPage.Content, themedView.Content);
|
||||
await _mockThemePageRenderer.Received(1).RenderAsync(
|
||||
Arg.Is<ThemePageDto>(page =>
|
||||
page.PageKey == "playlists/item" &&
|
||||
page.Title == expectedPlaylist.Name &&
|
||||
page.Description == expectedPlaylist.Description &&
|
||||
Equals(page.PageData["isNew"], false) &&
|
||||
string.Equals(page.PageData["playlistId"] as string, expectedPlaylist.Id.ToString(), StringComparison.Ordinal) &&
|
||||
Equals(page.PageData["entriesPerPage"], 200) &&
|
||||
HasPlaylistJson(page, expectedPlaylist)),
|
||||
Arg.Is<string?>(requestedThemeId => requestedThemeId == null),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenPlaylistHasNoDescription_ShouldRenderAnEmptyDescription()
|
||||
{
|
||||
// Arrange
|
||||
PlaylistDto expectedPlaylist = _playlistDtoFixture.Create(includeDescription: false);
|
||||
SetRoutePlaylistId(expectedPlaylist.Id);
|
||||
_mockApiHttpClient.GetAsync<PlaylistDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedPlaylist);
|
||||
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_themePageRenderResultDtoFixture.Create()));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockThemePageRenderer.Received(1).RenderAsync(
|
||||
Arg.Is<ThemePageDto>(page => string.Equals(page.Description, string.Empty, StringComparison.Ordinal)),
|
||||
Arg.Any<string?>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenPlaylistIsReturned_ShouldExposeEveryPageDataUrl()
|
||||
{
|
||||
// Arrange
|
||||
PlaylistDto expectedPlaylist = _playlistDtoFixture.Create();
|
||||
SetRoutePlaylistId(expectedPlaylist.Id);
|
||||
_mockApiHttpClient.GetAsync<PlaylistDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedPlaylist);
|
||||
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_themePageRenderResultDtoFixture.Create()));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockThemePageRenderer.Received(1).RenderAsync(
|
||||
Arg.Is<ThemePageDto>(page =>
|
||||
string.Equals(page.PageData["createPlaylistUrl"] as string, "http://localhost/en-us/playlists/api-create-playlist", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["itemUrl"] as string, $"http://localhost/en-us/playlists/item/{ZERO_GUID}", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["getPlaylistUrl"] as string, "http://localhost/en-us/playlists/item/get-playlist", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["updatePlaylistUrl"] as string, "http://localhost/en-us/playlists/item/update-playlist", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["deletePlaylistUrl"] as string, "http://localhost/en-us/playlists/item/delete-playlist", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["addEntryUrl"] as string, "http://localhost/en-us/playlists/item/add-entry", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["removeEntryUrl"] as string, "http://localhost/en-us/playlists/item/remove-entry", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["moveEntryUrl"] as string, "http://localhost/en-us/playlists/item/move-entry", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["getEnabledLibrariesUrl"] as string, "http://localhost/en-us/libraries/manage/api-get-enabled-libraries", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["getArtistsUrl"] as string, "http://localhost/en-us/library/audio-library/music-library/artists/api-get-artists", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["getArtistAlbumsUrl"] as string, $"http://localhost/en-us/library/audio-library/music-library/artists/{ZERO_GUID}/albums/api-get-albums", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["getAlbumTracksUrl"] as string, $"http://localhost/en-us/library/audio-library/music-library/artists/{ZERO_GUID}/albums/{ZERO_GUID}/tracks/api-get-tracks", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["indexUrl"] as string, "http://localhost/en-us/playlists", StringComparison.Ordinal)),
|
||||
Arg.Any<string?>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
_mockUrlService.Received(1).GetAbsoluteUrl(WebRoutes.Playlists.ITEM, Arg.Is<object?>(routeValues => HasRouteValue(routeValues, "playlistId", Guid.Empty)));
|
||||
_mockUrlService.Received(1).GetAbsoluteUrl(WebRoutes.Playlists.GET_PLAYLIST, Arg.Is<object?>(routeValues => HasRouteValue(routeValues, "playlistId", expectedPlaylist.Id)));
|
||||
_mockUrlService.Received(1).GetAbsoluteUrl(WebRoutes.Playlists.UPDATE_PLAYLIST, Arg.Is<object?>(routeValues => HasRouteValue(routeValues, "playlistId", expectedPlaylist.Id)));
|
||||
_mockUrlService.Received(1).GetAbsoluteUrl(WebRoutes.Playlists.DELETE_PLAYLIST, Arg.Is<object?>(routeValues => HasRouteValue(routeValues, "playlistId", expectedPlaylist.Id)));
|
||||
_mockUrlService.Received(1).GetAbsoluteUrl(WebRoutes.Playlists.ADD_PLAYLIST_ENTRY, Arg.Is<object?>(routeValues => HasRouteValue(routeValues, "playlistId", expectedPlaylist.Id)));
|
||||
_mockUrlService.Received(1).GetAbsoluteUrl(WebRoutes.Playlists.REMOVE_PLAYLIST_ENTRY, Arg.Is<object?>(routeValues =>
|
||||
HasRouteValue(routeValues, "playlistId", expectedPlaylist.Id) && HasRouteValue(routeValues, "playlistEntryId", Guid.Empty)));
|
||||
_mockUrlService.Received(1).GetAbsoluteUrl(WebRoutes.Playlists.MOVE_PLAYLIST_ENTRY, Arg.Is<object?>(routeValues =>
|
||||
HasRouteValue(routeValues, "playlistId", expectedPlaylist.Id) && HasRouteValue(routeValues, "playlistEntryId", Guid.Empty)));
|
||||
_mockUrlService.Received(1).GetAbsoluteUrl(WebRoutes.Music.GET_ARTIST_ALBUMS, Arg.Is<object?>(routeValues => HasRouteValue(routeValues, "artistId", Guid.Empty)));
|
||||
_mockUrlService.Received(1).GetAbsoluteUrl(WebRoutes.Music.GET_ALBUM_TRACKS, Arg.Is<object?>(routeValues =>
|
||||
HasRouteValue(routeValues, "artistId", Guid.Empty) && HasRouteValue(routeValues, "albumId", Guid.Empty)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenPlaylistIsReturned_ShouldExposeTheAntiforgeryTokenAndTheLocalizedStrings()
|
||||
{
|
||||
// Arrange
|
||||
PlaylistDto expectedPlaylist = _playlistDtoFixture.Create();
|
||||
SetRoutePlaylistId(expectedPlaylist.Id);
|
||||
_mockApiHttpClient.GetAsync<PlaylistDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedPlaylist);
|
||||
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_themePageRenderResultDtoFixture.Create()));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.IsType<RazorViewResult>(result);
|
||||
_mockAntiforgery.Received(1).GetAndStoreTokens(_sut.HttpContext);
|
||||
await _mockThemePageRenderer.Received(1).RenderAsync(
|
||||
Arg.Is<ThemePageDto>(page =>
|
||||
string.Equals(page.PageData["antiforgeryToken"] as string, "request-token", StringComparison.Ordinal) &&
|
||||
HasDocumentedLocalizedStrings(page)),
|
||||
Arg.Any<string?>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSetPrivateNoStoreAndCookieVaryHeaders()
|
||||
{
|
||||
// Arrange
|
||||
PlaylistDto expectedPlaylist = _playlistDtoFixture.Create();
|
||||
SetRoutePlaylistId(expectedPlaylist.Id);
|
||||
_mockApiHttpClient.GetAsync<PlaylistDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedPlaylist);
|
||||
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_themePageRenderResultDtoFixture.Create()));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString());
|
||||
Assert.Equal("Cookie", _sut.HttpContext.Response.Headers["Vary"].ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenPlaylistIdIsAValidGuid_ShouldRequestThePlaylistOnce()
|
||||
{
|
||||
// Arrange
|
||||
PlaylistDto expectedPlaylist = _playlistDtoFixture.Create();
|
||||
SetRoutePlaylistId(expectedPlaylist.Id);
|
||||
_mockApiHttpClient.GetAsync<PlaylistDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedPlaylist);
|
||||
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_themePageRenderResultDtoFixture.Create()));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PlaylistDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == $"users/me/playlists/{expectedPlaylist.Id}?currentPage=1&perPage=200"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenPlaylistIdIsAnUppercaseGuid_ShouldForwardItInLowercase()
|
||||
{
|
||||
// Arrange
|
||||
PlaylistDto expectedPlaylist = _playlistDtoFixture.Create();
|
||||
SetRoutePlaylistId(s_playlistId.ToString().ToUpperInvariant());
|
||||
_mockApiHttpClient.GetAsync<PlaylistDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedPlaylist);
|
||||
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_themePageRenderResultDtoFixture.Create()));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PlaylistDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == $"users/me/playlists/{s_playlistId}?currentPage=1&perPage=200"),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockApiHttpClient.DidNotReceive().GetAsync<PlaylistDto>(
|
||||
Arg.Is<string>(endpoint => endpoint.Contains(s_playlistId.ToString().ToUpperInvariant(), StringComparison.Ordinal)),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenPlaylistIdIsNotAGuid_ShouldForwardTheEmptyGuid()
|
||||
{
|
||||
// Arrange
|
||||
SetRoutePlaylistId("not-a-guid");
|
||||
_mockApiHttpClient.GetAsync<PlaylistDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_playlistDtoFixture.Create());
|
||||
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_themePageRenderResultDtoFixture.Create()));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PlaylistDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == $"users/me/playlists/{ZERO_GUID}?currentPage=1&perPage=200"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenPlaylistIdRouteValueIsMissing_ShouldForwardTheEmptyGuid()
|
||||
{
|
||||
// Arrange
|
||||
_mockApiHttpClient.GetAsync<PlaylistDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_playlistDtoFixture.Create());
|
||||
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_themePageRenderResultDtoFixture.Create()));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PlaylistDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == $"users/me/playlists/{ZERO_GUID}?currentPage=1&perPage=200"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // basic SQL injection
|
||||
[InlineData("1;DROP TABLE")] // destructive injection
|
||||
[InlineData("../../admin")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // markup injection
|
||||
[InlineData("𝕡𝕝𝕒𝕪𝕝𝕚𝕤𝕥")] // unicode payload
|
||||
public async Task ExecuteAsync_WhenPlaylistIdIsCrafted_ShouldNormalizeItAndNeverForwardTheRawValue(string payload)
|
||||
{
|
||||
// Arrange
|
||||
SetRoutePlaylistId(payload);
|
||||
_mockApiHttpClient.GetAsync<PlaylistDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_playlistDtoFixture.Create());
|
||||
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_themePageRenderResultDtoFixture.Create()));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PlaylistDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == $"users/me/playlists/{ZERO_GUID}?currentPage=1&perPage=200"),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockApiHttpClient.DidNotReceive().GetAsync<PlaylistDto>(
|
||||
Arg.Is<string>(endpoint => endpoint.Contains(payload, StringComparison.Ordinal)),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenThemeRenderingFails_ShouldFallBackToTheRazorViewWithThePlaylist()
|
||||
{
|
||||
// Arrange
|
||||
PlaylistDto expectedPlaylist = _playlistDtoFixture.Create(name: "Evening listening");
|
||||
SetRoutePlaylistId(expectedPlaylist.Id);
|
||||
_mockApiHttpClient.GetAsync<PlaylistDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedPlaylist);
|
||||
_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(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("/Core/Views/Playlists/Item.cshtml", GetRenderedViewName(result));
|
||||
IReadOnlyDictionary<string, object?> viewData = GetRenderedViewData(result);
|
||||
Assert.Equal(expectedPlaylist.Name, viewData["Title"]);
|
||||
Assert.False((bool)viewData["IsNew"]!);
|
||||
PlaylistDto playlist = Assert.IsType<PlaylistDto>(GetRenderedModel(result));
|
||||
Assert.Equal(expectedPlaylist.Id, playlist.Id);
|
||||
Assert.Equal(expectedPlaylist.Name, playlist.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
PlaylistDto expectedPlaylist = _playlistDtoFixture.Create();
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
SetRoutePlaylistId(expectedPlaylist.Id);
|
||||
_mockApiHttpClient.GetAsync<PlaylistDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.ArgAt<CancellationToken>(1).ThrowIfCancellationRequested();
|
||||
return expectedPlaylist;
|
||||
}, callInfo.ArgAt<CancellationToken>(1)));
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(EmptyRequest.Instance, cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the absolute URLs that the endpoint resolves for the playlist page.
|
||||
/// </summary>
|
||||
private void StubUrls()
|
||||
{
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Playlists.CREATE_PLAYLIST)
|
||||
.Returns("http://localhost/en-us/playlists/api-create-playlist");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Playlists.ITEM, Arg.Any<object?>())
|
||||
.Returns($"http://localhost/en-us/playlists/item/{ZERO_GUID}");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Playlists.GET_PLAYLIST, Arg.Any<object?>())
|
||||
.Returns("http://localhost/en-us/playlists/item/get-playlist");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Playlists.UPDATE_PLAYLIST, Arg.Any<object?>())
|
||||
.Returns("http://localhost/en-us/playlists/item/update-playlist");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Playlists.DELETE_PLAYLIST, Arg.Any<object?>())
|
||||
.Returns("http://localhost/en-us/playlists/item/delete-playlist");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Playlists.ADD_PLAYLIST_ENTRY, Arg.Any<object?>())
|
||||
.Returns("http://localhost/en-us/playlists/item/add-entry");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Playlists.REMOVE_PLAYLIST_ENTRY, Arg.Any<object?>())
|
||||
.Returns("http://localhost/en-us/playlists/item/remove-entry");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Playlists.MOVE_PLAYLIST_ENTRY, Arg.Any<object?>())
|
||||
.Returns("http://localhost/en-us/playlists/item/move-entry");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.GET_ENABLED_LIBRARIES)
|
||||
.Returns("http://localhost/en-us/libraries/manage/api-get-enabled-libraries");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Music.GET_ARTISTS)
|
||||
.Returns("http://localhost/en-us/library/audio-library/music-library/artists/api-get-artists");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Music.GET_ARTIST_ALBUMS, Arg.Any<object?>())
|
||||
.Returns($"http://localhost/en-us/library/audio-library/music-library/artists/{ZERO_GUID}/albums/api-get-albums");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Music.GET_ALBUM_TRACKS, Arg.Any<object?>())
|
||||
.Returns($"http://localhost/en-us/library/audio-library/music-library/artists/{ZERO_GUID}/albums/{ZERO_GUID}/tracks/api-get-tracks");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Playlists.INDEX)
|
||||
.Returns("http://localhost/en-us/playlists");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the serialized playlist of the page matches the playlist returned by the API.
|
||||
/// </summary>
|
||||
/// <param name="page">The page model passed to the theme renderer.</param>
|
||||
/// <param name="expectedPlaylist">The playlist returned by the API.</param>
|
||||
/// <returns><see langword="true"/> when the serialized playlist matches the returned playlist; otherwise <see langword="false"/>.</returns>
|
||||
private static bool HasPlaylistJson(ThemePageDto page, PlaylistDto expectedPlaylist)
|
||||
{
|
||||
if (!page.PageData.TryGetValue("playlistJson", out object? value) || value is not string playlistJson)
|
||||
return false;
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(playlistJson);
|
||||
JsonElement root = jsonDocument.RootElement;
|
||||
JsonElement entries = root.GetProperty("entries");
|
||||
return root.GetProperty("id").GetGuid() == expectedPlaylist.Id
|
||||
&& string.Equals(root.GetProperty("name").GetString(), expectedPlaylist.Name, StringComparison.Ordinal)
|
||||
&& string.Equals(root.GetProperty("description").GetString(), expectedPlaylist.Description, StringComparison.Ordinal)
|
||||
&& string.Equals(root.GetProperty("type").GetString(), nameof(PlaylistType.Music), StringComparison.Ordinal)
|
||||
&& entries.GetProperty("currentPage").GetInt32() == expectedPlaylist.Entries.CurrentPage
|
||||
&& entries.GetProperty("perPage").GetInt32() == expectedPlaylist.Entries.PerPage
|
||||
&& entries.GetProperty("count").GetInt32() == expectedPlaylist.Entries.Count
|
||||
&& entries.GetProperty("numberOfPages").GetInt32() == expectedPlaylist.Entries.NumberOfPages
|
||||
&& entries.GetProperty("data").GetArrayLength() == expectedPlaylist.Entries.Data.Count;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the page data carries the localized strings of the playlist page.
|
||||
/// </summary>
|
||||
/// <param name="page">The page model passed to the theme renderer.</param>
|
||||
/// <returns><see langword="true"/> when the localized strings are exposed under the <c>strings</c> key; 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;
|
||||
return string.Equals(strings["Save"] as string, "Save", StringComparison.Ordinal)
|
||||
&& string.Equals(strings["Delete"] as string, "Delete", StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the named property of an anonymous route values object holds the expected 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>
|
||||
/// <param name="expected">The expected Guid value.</param>
|
||||
/// <returns><see langword="true"/> when the property holds the expected Guid; otherwise <see langword="false"/>.</returns>
|
||||
private static bool HasRouteValue(object? routeValues, string propertyName, Guid expected)
|
||||
{
|
||||
if (routeValues is null)
|
||||
return false;
|
||||
PropertyInfo? property = routeValues.GetType().GetProperty(propertyName);
|
||||
return property is not null && property.GetValue(routeValues) is Guid value && value == expected;
|
||||
}
|
||||
|
||||
/// <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>
|
||||
/// Reads the private view data 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 view data entries passed to the rendered view.</returns>
|
||||
private static IReadOnlyDictionary<string, object?> GetRenderedViewData(IResult result)
|
||||
{
|
||||
RazorViewResult viewResult = Assert.IsType<RazorViewResult>(result);
|
||||
FieldInfo? viewDataField = typeof(RazorViewResult).GetField("_viewData", BindingFlags.Instance | BindingFlags.NonPublic);
|
||||
Assert.NotNull(viewDataField);
|
||||
return (IReadOnlyDictionary<string, object?>)viewDataField.GetValue(viewResult)!;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the route value of the playlist identifier route segment.
|
||||
/// </summary>
|
||||
/// <param name="playlistId">The value of the playlist identifier route segment.</param>
|
||||
private void SetRoutePlaylistId(object playlistId)
|
||||
{
|
||||
_sut.HttpContext.Request.RouteValues["playlistId"] = playlistId;
|
||||
}
|
||||
}
|
||||
@@ -128,6 +128,38 @@ public class ThemeNavBuilderTests
|
||||
Assert.Contains(audioEntry.Children, entry => entry.Label == "Localized-Interviews" && entry.Url == "library/audio/interviews");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task BuildAsync_WhenUserIsAuthenticated_ShouldIncludeFavoritesEntryInTheLibrarySection()
|
||||
{
|
||||
// Arrange
|
||||
_mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(user: TestHttpContextFactory.CreateAuthenticatedUser()));
|
||||
|
||||
// Act
|
||||
ThemeNavMenuDto result = await _sut.BuildAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
ThemeNavSectionDto mobileLibrarySection = FindSection(result, "Localized-Library")!;
|
||||
Assert.Contains(mobileLibrarySection.Items, entry => entry.Label == "Localized-Favorites" && entry.Url == "http://localhost/en-us/favorites");
|
||||
ThemeNavSectionDto menubarLibrarySection = FindSection(result, "Localized-Library", isMobile: false)!;
|
||||
Assert.Contains(menubarLibrarySection.Items, entry => entry.Label == "Localized-Favorites" && entry.Url == "http://localhost/en-us/favorites");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task BuildAsync_WhenUserIsAnonymous_ShouldNotIncludeAnyFavoritesEntry()
|
||||
{
|
||||
// Arrange
|
||||
_mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(user: null));
|
||||
|
||||
// Act
|
||||
ThemeNavMenuDto result = await _sut.BuildAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.DoesNotContain(FlattenEntries(result.MobileSections), entry => entry.Label == "Localized-Favorites");
|
||||
Assert.DoesNotContain(FlattenEntries(result.MenubarSections), entry => entry.Label == "Localized-Favorites");
|
||||
Assert.DoesNotContain(FlattenEntries(result.MobileSections), entry => entry.Url == "http://localhost/en-us/favorites");
|
||||
Assert.DoesNotContain(FlattenEntries(result.MenubarSections), entry => entry.Url == "http://localhost/en-us/favorites");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task BuildAsync_WhenUserIsAdmin_ShouldIncludeAdministratorSection()
|
||||
{
|
||||
@@ -260,10 +292,38 @@ public class ThemeNavBuilderTests
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Admin.MANAGE_THEMES).Returns("http://localhost/en-us/admin/manage-themes");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.INDEX).Returns("http://localhost/en-us/libraries/manage");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.ADD_LIBRARY).Returns("http://localhost/en-us/libraries/manage/item");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Favorites.INDEX).Returns("http://localhost/en-us/favorites");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Settings.INDEX).Returns("http://localhost/en-us/tools/settings");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Language.SET_LANGUAGE).Returns("http://localhost/en-us/tools/language/set-language");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Flattens the entries of the given sections, including the nested children of every submenu.
|
||||
/// </summary>
|
||||
/// <param name="sections">The sections whose entries are flattened.</param>
|
||||
/// <returns>The entries of the sections, depth first.</returns>
|
||||
private static IEnumerable<ThemeNavEntryDto> FlattenEntries(IEnumerable<ThemeNavSectionDto> sections)
|
||||
{
|
||||
foreach (ThemeNavSectionDto section in sections)
|
||||
foreach (ThemeNavEntryDto entry in FlattenEntries(section.Items))
|
||||
yield return entry;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Flattens the given entries, including the nested children of every submenu.
|
||||
/// </summary>
|
||||
/// <param name="entries">The entries to flatten.</param>
|
||||
/// <returns>The entries, depth first.</returns>
|
||||
private static IEnumerable<ThemeNavEntryDto> FlattenEntries(IEnumerable<ThemeNavEntryDto> entries)
|
||||
{
|
||||
foreach (ThemeNavEntryDto entry in entries)
|
||||
{
|
||||
yield return entry;
|
||||
foreach (ThemeNavEntryDto child in FlattenEntries(entry.Children))
|
||||
yield return child;
|
||||
}
|
||||
}
|
||||
|
||||
private static ThemeNavSectionDto? FindSection(ThemeNavMenuDto menu, string label, bool isMobile = true)
|
||||
{
|
||||
IReadOnlyList<ThemeNavSectionDto> sections = isMobile ? menu.MobileSections : menu.MenubarSections;
|
||||
|
||||
Reference in new issue
Block a user