mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 08:11:10 +00:00
Renames project paths from Lumina to Nemera
This commit is contained in:
1 parent
ce6fddb4c9
commit
0f659a4877
6450 files changed
No files matched your search
+145
@@ -0,0 +1,145 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.DeleteMusicAlbum;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.DeleteMusicAlbum;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="DeleteMusicAlbumEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteMusicAlbumEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly DeleteMusicAlbumEndpoint _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteMusicAlbumEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public DeleteMusicAlbumEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<DeleteMusicAlbumEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldDeleteAlbumViaApiAndReturnSuccessWithoutData()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ConfigureRequest(artistId.ToString(), albumId.ToString(), libraryId);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
BuildExpectedEndpoint(libraryId, artistId, albumId),
|
||||
Arg.Any<CancellationToken>());
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.False(jsonDocument.RootElement.TryGetProperty("data", out JsonElement _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteIdsAreNotParseable_ShouldForwardGuidEmptyIdsToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ConfigureRequest("not-a-guid", "not-a-guid", libraryId);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
BuildExpectedEndpoint(libraryId, Guid.Empty, Guid.Empty),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteIdsAreMissing_ShouldForwardGuidEmptyIdsToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={libraryId}");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
BuildExpectedEndpoint(libraryId, Guid.Empty, Guid.Empty),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenLibraryQueryIdIsNotParseable_ShouldForwardGuidEmptyLibraryIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
ConfigureRequest(artistId.ToString(), albumId.ToString(), "not-a-guid");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
BuildExpectedEndpoint(Guid.Empty, artistId, albumId),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the route and query values the endpoint reads the album identities from.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The raw route value of the artist Id.</param>
|
||||
/// <param name="albumId">The raw route value of the album Id.</param>
|
||||
/// <param name="libraryId">The raw query value of the library Id.</param>
|
||||
private void ConfigureRequest(string artistId, string albumId, Guid libraryId)
|
||||
{
|
||||
ConfigureRequest(artistId, albumId, libraryId.ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the route and query values the endpoint reads the album identities from.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The raw route value of the artist Id.</param>
|
||||
/// <param name="albumId">The raw route value of the album Id.</param>
|
||||
/// <param name="libraryId">The raw query value of the library Id.</param>
|
||||
private void ConfigureRequest(string artistId, string albumId, string libraryId)
|
||||
{
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = artistId;
|
||||
_sut.HttpContext.Request.RouteValues["albumId"] = albumId;
|
||||
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={libraryId}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the upstream endpoint the album deletion is expected to be sent to.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The normalized Id of the media library.</param>
|
||||
/// <param name="artistId">The normalized Id of the artist.</param>
|
||||
/// <param name="albumId">The normalized Id of the album.</param>
|
||||
/// <returns>The expected upstream endpoint.</returns>
|
||||
private static string BuildExpectedEndpoint(Guid libraryId, Guid artistId, Guid albumId)
|
||||
{
|
||||
return ApiRoutes.Music.DELETE_ALBUM
|
||||
.Replace("{libraryId}", libraryId.ToString())
|
||||
.Replace("{artistId}", artistId.ToString())
|
||||
.Replace("{albumId}", albumId.ToString());
|
||||
}
|
||||
}
|
||||
+168
@@ -0,0 +1,168 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetArtistAlbums;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetArtistAlbums;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetArtistAlbumsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetArtistAlbumsEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly GetArtistAlbumsEndpoint _sut;
|
||||
private readonly GetArtistAlbumsLiteRequestFixture _getArtistAlbumsLiteRequestFixture = new();
|
||||
private readonly PaginatedDtoFixture<MusicAlbumLiteDto> _paginatedMusicAlbumLiteDtoFixture = new();
|
||||
private readonly MusicAlbumLiteDtoFixture _musicAlbumLiteDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetArtistAlbumsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetArtistAlbumsEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<GetArtistAlbumsEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalledWithPagination_ShouldRequestAlbumsWithQueryParameters()
|
||||
{
|
||||
// Arrange
|
||||
GetArtistAlbumsLiteRequest request = _getArtistAlbumsLiteRequestFixture.Create(currentPage: 2, perPage: 48);
|
||||
_mockApiHttpClient.GetAsync<PaginatedDto<MusicAlbumLiteDto>>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedMusicAlbumLiteDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedDto<MusicAlbumLiteDto>>(
|
||||
Arg.Is<string>(endpoint => endpoint == $"{BuildExpectedEndpoint(request.LibraryId, Guid.Parse(request.ArtistId))}?currentPage=2&perPage=48"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalledWithoutPagination_ShouldRequestAlbumsWithoutQueryParameters()
|
||||
{
|
||||
// Arrange
|
||||
GetArtistAlbumsLiteRequest request = _getArtistAlbumsLiteRequestFixture.Create();
|
||||
_mockApiHttpClient.GetAsync<PaginatedDto<MusicAlbumLiteDto>>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedMusicAlbumLiteDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedDto<MusicAlbumLiteDto>>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(request.LibraryId, Guid.Parse(request.ArtistId))),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOnlyCurrentPageIsProvided_ShouldAppendOnlyCurrentPage()
|
||||
{
|
||||
// Arrange
|
||||
GetArtistAlbumsLiteRequest request = _getArtistAlbumsLiteRequestFixture.Create(currentPage: 3);
|
||||
_mockApiHttpClient.GetAsync<PaginatedDto<MusicAlbumLiteDto>>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedMusicAlbumLiteDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedDto<MusicAlbumLiteDto>>(
|
||||
Arg.Is<string>(endpoint => endpoint == $"{BuildExpectedEndpoint(request.LibraryId, Guid.Parse(request.ArtistId))}?currentPage=3"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOnlyPerPageIsProvided_ShouldAppendOnlyPerPage()
|
||||
{
|
||||
// Arrange
|
||||
GetArtistAlbumsLiteRequest request = _getArtistAlbumsLiteRequestFixture.Create(perPage: 24);
|
||||
_mockApiHttpClient.GetAsync<PaginatedDto<MusicAlbumLiteDto>>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedMusicAlbumLiteDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedDto<MusicAlbumLiteDto>>(
|
||||
Arg.Is<string>(endpoint => endpoint == $"{BuildExpectedEndpoint(request.LibraryId, Guid.Parse(request.ArtistId))}?perPage=24"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenArtistIdIsNotParseable_ShouldForwardGuidEmptyArtistIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
GetArtistAlbumsLiteRequest request = _getArtistAlbumsLiteRequestFixture.Create(artistId: "not-a-guid", currentPage: 1, perPage: 20);
|
||||
_mockApiHttpClient.GetAsync<PaginatedDto<MusicAlbumLiteDto>>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedMusicAlbumLiteDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedDto<MusicAlbumLiteDto>>(
|
||||
Arg.Is<string>(endpoint => endpoint == $"{BuildExpectedEndpoint(request.LibraryId, Guid.Empty)}?currentPage=1&perPage=20"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsPaginatedAlbums_ShouldReturnSuccessJsonWithAlbums()
|
||||
{
|
||||
// Arrange
|
||||
GetArtistAlbumsLiteRequest request = _getArtistAlbumsLiteRequestFixture.Create();
|
||||
PaginatedDto<MusicAlbumLiteDto> expectedResponse = _paginatedMusicAlbumLiteDtoFixture.Create(
|
||||
data: [_musicAlbumLiteDtoFixture.Create(title: "Test Album")],
|
||||
currentPage: 1,
|
||||
perPage: 20,
|
||||
count: 1,
|
||||
numberOfPages: 1);
|
||||
_mockApiHttpClient.GetAsync<PaginatedDto<MusicAlbumLiteDto>>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedResponse);
|
||||
|
||||
// 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(1, data.GetProperty("currentPage").GetInt32());
|
||||
Assert.Equal(1, data.GetProperty("data").GetArrayLength());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the upstream endpoint the artist album retrieval is expected to be sent to, without query parameters.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library.</param>
|
||||
/// <param name="artistId">The normalized Id of the artist.</param>
|
||||
/// <returns>The expected upstream endpoint.</returns>
|
||||
private static string BuildExpectedEndpoint(Guid libraryId, Guid artistId)
|
||||
{
|
||||
return ApiRoutes.Music.GET_ARTIST_ALBUMS_LITE
|
||||
.Replace("{libraryId}", libraryId.ToString())
|
||||
.Replace("{artistId}", artistId.ToString());
|
||||
}
|
||||
}
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetMusicAlbum;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetMusicAlbum;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetMusicAlbumEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetMusicAlbumEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly GetMusicAlbumEndpoint _sut;
|
||||
private readonly GetMusicAlbumViewRequestFixture _getMusicAlbumViewRequestFixture = new();
|
||||
private readonly MusicAlbumDtoFixture _musicAlbumDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetMusicAlbumEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetMusicAlbumEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<GetMusicAlbumEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldRequestAlbumFromApiWithNormalizedIds()
|
||||
{
|
||||
// Arrange
|
||||
GetMusicAlbumViewRequest request = _getMusicAlbumViewRequestFixture.Create();
|
||||
MusicAlbumDto expectedAlbum = _musicAlbumDtoFixture.Create();
|
||||
_mockApiHttpClient.GetAsync<MusicAlbumDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedAlbum);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<MusicAlbumDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(request.LibraryId, Guid.Parse(request.ArtistId), Guid.Parse(request.AlbumId))),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteIdsAreNotParseable_ShouldForwardGuidEmptyIdsToApi()
|
||||
{
|
||||
// Arrange
|
||||
GetMusicAlbumViewRequest request = _getMusicAlbumViewRequestFixture.Create(artistId: "not-a-guid", albumId: "' OR '1'='1");
|
||||
_mockApiHttpClient.GetAsync<MusicAlbumDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_musicAlbumDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<MusicAlbumDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(request.LibraryId, Guid.Empty, Guid.Empty)),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteIdsAreEmpty_ShouldForwardGuidEmptyIdsToApi()
|
||||
{
|
||||
// Arrange
|
||||
GetMusicAlbumViewRequest request = _getMusicAlbumViewRequestFixture.Create(artistId: string.Empty, albumId: string.Empty);
|
||||
_mockApiHttpClient.GetAsync<MusicAlbumDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_musicAlbumDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<MusicAlbumDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(request.LibraryId, Guid.Empty, Guid.Empty)),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsAlbum_ShouldReturnSuccessJsonWithAlbum()
|
||||
{
|
||||
// Arrange
|
||||
GetMusicAlbumViewRequest request = _getMusicAlbumViewRequestFixture.Create();
|
||||
MusicAlbumDto expectedAlbum = _musicAlbumDtoFixture.Create();
|
||||
_mockApiHttpClient.GetAsync<MusicAlbumDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedAlbum);
|
||||
|
||||
// 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());
|
||||
Assert.Equal(expectedAlbum.Id, jsonDocument.RootElement.GetProperty("data").GetProperty("id").GetGuid());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the upstream endpoint the album retrieval is expected to be sent to.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The normalized Id of the media library.</param>
|
||||
/// <param name="artistId">The normalized Id of the artist.</param>
|
||||
/// <param name="albumId">The normalized Id of the album.</param>
|
||||
/// <returns>The expected upstream endpoint.</returns>
|
||||
private static string BuildExpectedEndpoint(Guid libraryId, Guid artistId, Guid albumId)
|
||||
{
|
||||
return ApiRoutes.Music.GET_ALBUM
|
||||
.Replace("{libraryId}", libraryId.ToString())
|
||||
.Replace("{artistId}", artistId.ToString())
|
||||
.Replace("{albumId}", albumId.ToString());
|
||||
}
|
||||
}
|
||||
+213
@@ -0,0 +1,213 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.RestoreMusicAlbum;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.RestoreMusicAlbum;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="RestoreMusicAlbumEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RestoreMusicAlbumEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly RestoreMusicAlbumEndpoint _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RestoreMusicAlbumEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public RestoreMusicAlbumEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<RestoreMusicAlbumEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("D")] // Standard hyphenated format.
|
||||
[InlineData("B")] // Braced format.
|
||||
[InlineData("N")] // Compact format.
|
||||
[InlineData("P")] // Parenthesized format.
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldRestoreAlbumViaApiWithNormalizedIdsAndReturnSuccessPayload(string guidFormat)
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ConfigureRequest(artistId.ToString(guidFormat), albumId.ToString(guidFormat), libraryId.ToString(guidFormat));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync(
|
||||
BuildExpectedEndpoint(libraryId, artistId, albumId),
|
||||
Arg.Any<CancellationToken>());
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("data").GetProperty("isRestored").GetBoolean());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenArtistRouteIdIsNotParseable_ShouldForwardGuidEmptyArtistIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ConfigureRequest("not-a-guid", albumId.ToString(), libraryId.ToString());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync(
|
||||
BuildExpectedEndpoint(libraryId, Guid.Empty, albumId),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenArtistRouteIdIsMissing_ShouldForwardGuidEmptyArtistIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ConfigureRequest(null, albumId.ToString(), libraryId.ToString());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync(
|
||||
BuildExpectedEndpoint(libraryId, Guid.Empty, albumId),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenAlbumRouteIdIsNotParseable_ShouldForwardGuidEmptyAlbumIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ConfigureRequest(artistId.ToString(), "not-a-guid", libraryId.ToString());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync(
|
||||
BuildExpectedEndpoint(libraryId, artistId, Guid.Empty),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenAlbumRouteIdIsMissing_ShouldForwardGuidEmptyAlbumIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ConfigureRequest(artistId.ToString(), null, libraryId.ToString());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync(
|
||||
BuildExpectedEndpoint(libraryId, artistId, Guid.Empty),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenLibraryQueryIdIsNotParseable_ShouldForwardGuidEmptyLibraryIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
ConfigureRequest(artistId.ToString(), albumId.ToString(), "not-a-guid");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync(
|
||||
BuildExpectedEndpoint(Guid.Empty, artistId, albumId),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenLibraryQueryIdIsMissing_ShouldForwardGuidEmptyLibraryIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
ConfigureRequest(artistId.ToString(), albumId.ToString(), null);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync(
|
||||
BuildExpectedEndpoint(Guid.Empty, artistId, albumId),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ConfigureRequest(artistId.ToString(), albumId.ToString(), libraryId.ToString());
|
||||
using CancellationTokenSource cancellationTokenSource = new();
|
||||
cancellationTokenSource.Cancel();
|
||||
_mockApiHttpClient.PostIgnoringResponseAsync(
|
||||
Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromCanceled(cancellationTokenSource.Token));
|
||||
|
||||
// Act & Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(
|
||||
() => _sut.ExecuteAsync(EmptyRequest.Instance, cancellationTokenSource.Token));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the route and query values the endpoint reads the album identity from.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The raw route value of the artist Id, or <see langword="null"/> to leave the route value missing.</param>
|
||||
/// <param name="albumId">The raw route value of the album Id, or <see langword="null"/> to leave the route value missing.</param>
|
||||
/// <param name="libraryId">The raw query value of the library Id, or <see langword="null"/> to leave the query string missing.</param>
|
||||
private void ConfigureRequest(string? artistId, string? albumId, string? libraryId)
|
||||
{
|
||||
if (artistId is not null)
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = artistId;
|
||||
if (albumId is not null)
|
||||
_sut.HttpContext.Request.RouteValues["albumId"] = albumId;
|
||||
if (libraryId is not null)
|
||||
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={libraryId}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the upstream endpoint the album restoration is expected to be sent to.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The normalized Id of the media library.</param>
|
||||
/// <param name="artistId">The normalized Id of the artist.</param>
|
||||
/// <param name="albumId">The normalized Id of the album.</param>
|
||||
/// <returns>The expected upstream endpoint.</returns>
|
||||
private static string BuildExpectedEndpoint(Guid libraryId, Guid artistId, Guid albumId)
|
||||
{
|
||||
return ApiRoutes.Music.RESTORE_ALBUM
|
||||
.Replace("{libraryId}", libraryId.ToString())
|
||||
.Replace("{artistId}", artistId.ToString())
|
||||
.Replace("{albumId}", albumId.ToString());
|
||||
}
|
||||
}
|
||||
+212
@@ -0,0 +1,212 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.SaveMusicAlbum;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.SaveMusicAlbum;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="SaveMusicAlbumEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SaveMusicAlbumEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly SaveMusicAlbumEndpoint _sut;
|
||||
private readonly UpdateMusicAlbumRequestFixture _updateMusicAlbumRequestFixture = new();
|
||||
private readonly MusicAlbumDtoFixture _musicAlbumDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SaveMusicAlbumEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public SaveMusicAlbumEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<SaveMusicAlbumEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldForwardUpdateMusicAlbumRequestToApiWithRouteAndQueryIds()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
UpdateMusicAlbumRequest request = _updateMusicAlbumRequestFixture.Create();
|
||||
MusicAlbumDto expectedAlbum = _musicAlbumDtoFixture.Create();
|
||||
_mockApiHttpClient.PutAsync<MusicAlbumDto, UpdateMusicAlbumRequest>(Arg.Any<string>(), Arg.Any<UpdateMusicAlbumRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedAlbum);
|
||||
ConfigureRequest(artistId.ToString(), albumId.ToString(), libraryId);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutAsync<MusicAlbumDto, UpdateMusicAlbumRequest>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(libraryId, artistId, albumId)),
|
||||
Arg.Is<UpdateMusicAlbumRequest>(forwardedRequest => forwardedRequest == request),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenArtistRouteIdIsNotParseable_ShouldForwardGuidEmptyArtistIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
const string MALICIOUS_ARTIST_ID = "not-a-guid";
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
UpdateMusicAlbumRequest request = _updateMusicAlbumRequestFixture.Create();
|
||||
_mockApiHttpClient.PutAsync<MusicAlbumDto, UpdateMusicAlbumRequest>(Arg.Any<string>(), Arg.Any<UpdateMusicAlbumRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_musicAlbumDtoFixture.Create());
|
||||
ConfigureRequest(MALICIOUS_ARTIST_ID, albumId.ToString(), libraryId);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutAsync<MusicAlbumDto, UpdateMusicAlbumRequest>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(libraryId, Guid.Empty, albumId)),
|
||||
Arg.Any<UpdateMusicAlbumRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenAlbumRouteIdIsNotParseable_ShouldForwardGuidEmptyAlbumIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
const string MALICIOUS_ALBUM_ID = "' OR '1'='1";
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
UpdateMusicAlbumRequest request = _updateMusicAlbumRequestFixture.Create();
|
||||
_mockApiHttpClient.PutAsync<MusicAlbumDto, UpdateMusicAlbumRequest>(Arg.Any<string>(), Arg.Any<UpdateMusicAlbumRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_musicAlbumDtoFixture.Create());
|
||||
ConfigureRequest(artistId.ToString(), MALICIOUS_ALBUM_ID, libraryId);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutAsync<MusicAlbumDto, UpdateMusicAlbumRequest>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(libraryId, artistId, Guid.Empty)),
|
||||
Arg.Any<UpdateMusicAlbumRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteIdsAreMissing_ShouldForwardGuidEmptyIdsToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
UpdateMusicAlbumRequest request = _updateMusicAlbumRequestFixture.Create();
|
||||
_mockApiHttpClient.PutAsync<MusicAlbumDto, UpdateMusicAlbumRequest>(Arg.Any<string>(), Arg.Any<UpdateMusicAlbumRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_musicAlbumDtoFixture.Create());
|
||||
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={libraryId}");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutAsync<MusicAlbumDto, UpdateMusicAlbumRequest>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(libraryId, Guid.Empty, Guid.Empty)),
|
||||
Arg.Any<UpdateMusicAlbumRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenLibraryQueryIdIsNotParseable_ShouldForwardGuidEmptyLibraryIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
const string MALICIOUS_LIBRARY_ID = "not-a-guid";
|
||||
UpdateMusicAlbumRequest request = _updateMusicAlbumRequestFixture.Create();
|
||||
_mockApiHttpClient.PutAsync<MusicAlbumDto, UpdateMusicAlbumRequest>(Arg.Any<string>(), Arg.Any<UpdateMusicAlbumRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_musicAlbumDtoFixture.Create());
|
||||
ConfigureRequest(artistId.ToString(), albumId.ToString(), MALICIOUS_LIBRARY_ID);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutAsync<MusicAlbumDto, UpdateMusicAlbumRequest>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(Guid.Empty, artistId, albumId)),
|
||||
Arg.Any<UpdateMusicAlbumRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsUpdatedAlbum_ShouldReturnSuccessJsonWithAlbum()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
UpdateMusicAlbumRequest request = _updateMusicAlbumRequestFixture.Create();
|
||||
MusicAlbumDto expectedAlbum = _musicAlbumDtoFixture.Create();
|
||||
_mockApiHttpClient.PutAsync<MusicAlbumDto, UpdateMusicAlbumRequest>(Arg.Any<string>(), Arg.Any<UpdateMusicAlbumRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedAlbum);
|
||||
ConfigureRequest(artistId.ToString(), albumId.ToString(), libraryId);
|
||||
|
||||
// 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());
|
||||
Assert.Equal(expectedAlbum.Id, jsonDocument.RootElement.GetProperty("data").GetProperty("id").GetGuid());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the route and query values the endpoint reads the album identities from.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The raw route value of the artist Id.</param>
|
||||
/// <param name="albumId">The raw route value of the album Id.</param>
|
||||
/// <param name="libraryId">The raw query value of the library Id.</param>
|
||||
private void ConfigureRequest(string artistId, string albumId, Guid libraryId)
|
||||
{
|
||||
ConfigureRequest(artistId, albumId, libraryId.ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the route and query values the endpoint reads the album identities from.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The raw route value of the artist Id.</param>
|
||||
/// <param name="albumId">The raw route value of the album Id.</param>
|
||||
/// <param name="libraryId">The raw query value of the library Id.</param>
|
||||
private void ConfigureRequest(string artistId, string albumId, string libraryId)
|
||||
{
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = artistId;
|
||||
_sut.HttpContext.Request.RouteValues["albumId"] = albumId;
|
||||
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={libraryId}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the upstream endpoint the album update is expected to be sent to.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The normalized Id of the media library.</param>
|
||||
/// <param name="artistId">The normalized Id of the artist.</param>
|
||||
/// <param name="albumId">The normalized Id of the album.</param>
|
||||
/// <returns>The expected upstream endpoint.</returns>
|
||||
private static string BuildExpectedEndpoint(Guid libraryId, Guid artistId, Guid albumId)
|
||||
{
|
||||
return ApiRoutes.Music.UPDATE_ALBUM
|
||||
.Replace("{libraryId}", libraryId.ToString())
|
||||
.Replace("{artistId}", artistId.ToString())
|
||||
.Replace("{albumId}", albumId.ToString());
|
||||
}
|
||||
}
|
||||
+313
@@ -0,0 +1,313 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.UpdateAlbumCover;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.Features;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.UpdateAlbumCover;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="UpdateAlbumCoverEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateAlbumCoverEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly UpdateAlbumCoverEndpoint _sut;
|
||||
private readonly UpdateMusicCoverDtoFixture _updateMusicCoverDtoFixture = new();
|
||||
private static readonly Guid s_libraryId = Guid.NewGuid();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateAlbumCoverEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public UpdateAlbumCoverEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<UpdateAlbumCoverEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalledWithFile_ShouldUploadCoverToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
_mockApiHttpClient.PutMultipartAsync<UpdateMusicCoverDto>(Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_updateMusicCoverDtoFixture.Create(coverPath: "/media/albums/cover.jpg"));
|
||||
ConfigureRequest(artistId, albumId, [1, 2, 3], "cover.jpg");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutMultipartAsync<UpdateMusicCoverDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(s_libraryId.ToString(), artistId, albumId)),
|
||||
Arg.Any<Stream>(),
|
||||
Arg.Is<string>(fileName => fileName == "cover.jpg"),
|
||||
Arg.Is<string>(fieldName => fieldName == "cover"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteIdsAreNotParseable_ShouldUploadCoverWithEmptyIds()
|
||||
{
|
||||
// Arrange
|
||||
_mockApiHttpClient.PutMultipartAsync<UpdateMusicCoverDto>(Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_updateMusicCoverDtoFixture.Create(coverPath: "/media/albums/cover.jpg"));
|
||||
ConfigureRequest("not-a-guid", "not-a-guid", [1, 2, 3], "cover.jpg");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutMultipartAsync<UpdateMusicCoverDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(s_libraryId.ToString(), Guid.Empty, Guid.Empty)),
|
||||
Arg.Any<Stream>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenLibraryQueryIdIsNotParseable_ShouldUploadCoverWithEmptyLibraryId()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
_mockApiHttpClient.PutMultipartAsync<UpdateMusicCoverDto>(Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_updateMusicCoverDtoFixture.Create(coverPath: "/media/albums/cover.jpg"));
|
||||
ConfigureRequest(artistId, albumId, [1, 2, 3], "cover.jpg");
|
||||
// The query value is normalized to a Guid before it is substituted into the upstream URL, so a crafted value can never escape its segment.
|
||||
_sut.HttpContext.Request.QueryString = new QueryString("?libraryId=not-a-library-guid");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutMultipartAsync<UpdateMusicCoverDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(Guid.Empty.ToString(), artistId, albumId)),
|
||||
Arg.Any<Stream>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenLibraryQueryIdIsMissing_ShouldUploadCoverWithEmptyLibraryId()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
_mockApiHttpClient.PutMultipartAsync<UpdateMusicCoverDto>(Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_updateMusicCoverDtoFixture.Create(coverPath: "/media/albums/cover.jpg"));
|
||||
ConfigureRequest(artistId, albumId, [1, 2, 3], "cover.jpg");
|
||||
_sut.HttpContext.Request.QueryString = new QueryString(string.Empty);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutMultipartAsync<UpdateMusicCoverDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(Guid.Empty.ToString(), artistId, albumId)),
|
||||
Arg.Any<Stream>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsCoverPath_ShouldReturnSuccessJsonWithPath()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
const string EXPECTED_PATH = "/media/albums/cover.jpg";
|
||||
_mockApiHttpClient.PutMultipartAsync<UpdateMusicCoverDto>(Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_updateMusicCoverDtoFixture.Create(coverPath: EXPECTED_PATH));
|
||||
ConfigureRequest(artistId, albumId, [1, 2, 3], "cover.jpg");
|
||||
|
||||
// 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.Equal(EXPECTED_PATH, jsonDocument.RootElement.GetProperty("data").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenFormHasNoFile_ShouldForwardRequestWithoutFileToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
const string EXPECTED_PATH = "/media/albums/cover.jpg";
|
||||
_mockApiHttpClient.PutMultipartAsync<UpdateMusicCoverDto>(Arg.Any<string>(), Arg.Any<Stream?>(), Arg.Any<string?>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_updateMusicCoverDtoFixture.Create(coverPath: EXPECTED_PATH));
|
||||
ConfigureRequestWithoutFiles(artistId, albumId);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutMultipartAsync<UpdateMusicCoverDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(s_libraryId.ToString(), artistId, albumId)),
|
||||
Arg.Is<Stream?>(stream => stream == null),
|
||||
Arg.Is<string?>(fileName => fileName == null),
|
||||
Arg.Is<string>(fieldName => fieldName == "cover"),
|
||||
Arg.Any<CancellationToken>());
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(EXPECTED_PATH, jsonDocument.RootElement.GetProperty("data").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRequestIsNotMultipart_ShouldForwardRequestWithoutFileToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
const string EXPECTED_PATH = "/media/albums/cover.jpg";
|
||||
_mockApiHttpClient.PutMultipartAsync<UpdateMusicCoverDto>(Arg.Any<string>(), Arg.Any<Stream?>(), Arg.Any<string?>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_updateMusicCoverDtoFixture.Create(coverPath: EXPECTED_PATH));
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString();
|
||||
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={s_libraryId}");
|
||||
_sut.HttpContext.Request.ContentType = "application/json";
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutMultipartAsync<UpdateMusicCoverDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(s_libraryId.ToString(), artistId, albumId)),
|
||||
Arg.Is<Stream?>(stream => stream == null),
|
||||
Arg.Is<string?>(fileName => fileName == null),
|
||||
Arg.Is<string>(fieldName => fieldName == "cover"),
|
||||
Arg.Any<CancellationToken>());
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(EXPECTED_PATH, jsonDocument.RootElement.GetProperty("data").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenFormIsMalformed_ShouldForwardRequestWithoutFileToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
const string EXPECTED_PATH = "/media/albums/cover.jpg";
|
||||
_mockApiHttpClient.PutMultipartAsync<UpdateMusicCoverDto>(Arg.Any<string>(), Arg.Any<Stream?>(), Arg.Any<string?>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_updateMusicCoverDtoFixture.Create(coverPath: EXPECTED_PATH));
|
||||
ConfigureMalformedRequest(artistId, albumId);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutMultipartAsync<UpdateMusicCoverDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(s_libraryId.ToString(), artistId, albumId)),
|
||||
Arg.Is<Stream?>(stream => stream == null),
|
||||
Arg.Is<string?>(fileName => fileName == null),
|
||||
Arg.Is<string>(fieldName => fieldName == "cover"),
|
||||
Arg.Any<CancellationToken>());
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(EXPECTED_PATH, jsonDocument.RootElement.GetProperty("data").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures a multipart form request carrying a single file.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The route Id of the artist.</param>
|
||||
/// <param name="albumId">The route Id of the album whose cover is uploaded.</param>
|
||||
/// <param name="content">The bytes of the uploaded file.</param>
|
||||
/// <param name="fileName">The name of the uploaded file.</param>
|
||||
private void ConfigureRequest(Guid artistId, Guid albumId, byte[] content, string fileName)
|
||||
{
|
||||
ConfigureRequest(artistId.ToString(), albumId.ToString(), content, fileName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures a multipart form request carrying a single file.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The raw route value of the artist Id.</param>
|
||||
/// <param name="albumId">The raw route value of the album Id.</param>
|
||||
/// <param name="content">The bytes of the uploaded file.</param>
|
||||
/// <param name="fileName">The name of the uploaded file.</param>
|
||||
private void ConfigureRequest(string artistId, string albumId, byte[] content, string fileName)
|
||||
{
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = artistId;
|
||||
_sut.HttpContext.Request.RouteValues["albumId"] = albumId;
|
||||
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={s_libraryId}");
|
||||
MemoryStream coverStream = new(content);
|
||||
IFormFile formFile = new FormFile(coverStream, 0, content.Length, "cover", fileName);
|
||||
FormFileCollection files = [formFile];
|
||||
IFormCollection form = new FormCollection([], files);
|
||||
_sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test";
|
||||
_sut.HttpContext.Features.Set<IFormFeature>(new FormFeature(form));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures a multipart form request without any file.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The route Id of the artist.</param>
|
||||
/// <param name="albumId">The route Id of the album whose cover is uploaded.</param>
|
||||
private void ConfigureRequestWithoutFiles(Guid artistId, Guid albumId)
|
||||
{
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString();
|
||||
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={s_libraryId}");
|
||||
IFormCollection form = new FormCollection([]);
|
||||
_sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test";
|
||||
_sut.HttpContext.Features.Set<IFormFeature>(new FormFeature(form));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures a multipart form request whose body cannot be parsed.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The route Id of the artist.</param>
|
||||
/// <param name="albumId">The route Id of the album whose cover is uploaded.</param>
|
||||
private void ConfigureMalformedRequest(Guid artistId, Guid albumId)
|
||||
{
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString();
|
||||
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={s_libraryId}");
|
||||
_sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test";
|
||||
IFormCollection malformedForm = Substitute.For<IFormCollection>();
|
||||
malformedForm.Files.Returns(_ => throw new InvalidDataException("Malformed multipart body."));
|
||||
_sut.HttpContext.Features.Set<IFormFeature>(new FormFeature(malformedForm));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the upstream endpoint the cover upload is expected to be sent to.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The raw Id of the media library.</param>
|
||||
/// <param name="artistId">The normalized Id of the artist.</param>
|
||||
/// <param name="albumId">The normalized Id of the album.</param>
|
||||
/// <returns>The expected upstream endpoint.</returns>
|
||||
private static string BuildExpectedEndpoint(string libraryId, Guid artistId, Guid albumId)
|
||||
{
|
||||
return ApiRoutes.Music.UPDATE_ALBUM_COVER
|
||||
.Replace("{libraryId}", libraryId)
|
||||
.Replace("{artistId}", artistId.ToString())
|
||||
.Replace("{albumId}", albumId.ToString());
|
||||
}
|
||||
}
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.DeleteMusicArtist;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.DeleteMusicArtist;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="DeleteMusicArtistEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteMusicArtistEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly DeleteMusicArtistEndpoint _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteMusicArtistEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public DeleteMusicArtistEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<DeleteMusicArtistEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldDeleteArtistViaApiAndReturnSuccessWithoutData()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ConfigureRequest(artistId.ToString(), libraryId.ToString());
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
BuildExpectedEndpoint(libraryId, artistId),
|
||||
Arg.Any<CancellationToken>());
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.False(jsonDocument.RootElement.TryGetProperty("data", out JsonElement _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenArtistRouteIdIsNotParseable_ShouldForwardGuidEmptyArtistIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ConfigureRequest("not-a-guid", libraryId.ToString());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
BuildExpectedEndpoint(libraryId, Guid.Empty),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenArtistRouteIdIsMissing_ShouldForwardGuidEmptyArtistIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={libraryId}");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
BuildExpectedEndpoint(libraryId, Guid.Empty),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenLibraryQueryIdIsNotParseable_ShouldForwardGuidEmptyLibraryIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
ConfigureRequest(artistId.ToString(), "not-a-guid");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
BuildExpectedEndpoint(Guid.Empty, artistId),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the route and query values the endpoint reads the artist identities from.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The raw route value of the artist Id.</param>
|
||||
/// <param name="libraryId">The raw query value of the library Id.</param>
|
||||
private void ConfigureRequest(string artistId, string libraryId)
|
||||
{
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = artistId;
|
||||
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={libraryId}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the upstream endpoint the artist deletion is expected to be sent to.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The normalized Id of the media library.</param>
|
||||
/// <param name="artistId">The normalized Id of the artist.</param>
|
||||
/// <returns>The expected upstream endpoint.</returns>
|
||||
private static string BuildExpectedEndpoint(Guid libraryId, Guid artistId)
|
||||
{
|
||||
return ApiRoutes.Music.DELETE_ARTIST
|
||||
.Replace("{libraryId}", libraryId.ToString())
|
||||
.Replace("{artistId}", artistId.ToString());
|
||||
}
|
||||
}
|
||||
+143
@@ -0,0 +1,143 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Artists;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetMusicArtist;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Artists;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetMusicArtist;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetMusicArtistEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetMusicArtistEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly GetMusicArtistEndpoint _sut;
|
||||
private readonly GetMusicArtistViewRequestFixture _getMusicArtistViewRequestFixture = new();
|
||||
private readonly MusicArtistDtoFixture _musicArtistDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetMusicArtistEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetMusicArtistEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<GetMusicArtistEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldRequestArtistFromApiWithNormalizedIds()
|
||||
{
|
||||
// Arrange
|
||||
GetMusicArtistViewRequest request = _getMusicArtistViewRequestFixture.Create();
|
||||
MusicArtistDto expectedArtist = _musicArtistDtoFixture.Create();
|
||||
_mockApiHttpClient.GetAsync<MusicArtistDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedArtist);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<MusicArtistDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(request.LibraryId, Guid.Parse(request.ArtistId))),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteArtistIdIsNotParseable_ShouldForwardGuidEmptyArtistIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
GetMusicArtistViewRequest request = _getMusicArtistViewRequestFixture.Create(artistId: "not-a-guid");
|
||||
_mockApiHttpClient.GetAsync<MusicArtistDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_musicArtistDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<MusicArtistDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(request.LibraryId, Guid.Empty)),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteArtistIdIsMissing_ShouldForwardGuidEmptyArtistIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
GetMusicArtistViewRequest request = _getMusicArtistViewRequestFixture.Create(artistId: string.Empty);
|
||||
_mockApiHttpClient.GetAsync<MusicArtistDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_musicArtistDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<MusicArtistDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(request.LibraryId, Guid.Empty)),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsArtist_ShouldReturnSuccessJsonWithArtist()
|
||||
{
|
||||
// Arrange
|
||||
GetMusicArtistViewRequest request = _getMusicArtistViewRequestFixture.Create();
|
||||
MusicArtistDto expectedArtist = _musicArtistDtoFixture.Create();
|
||||
_mockApiHttpClient.GetAsync<MusicArtistDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedArtist);
|
||||
|
||||
// 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());
|
||||
Assert.Equal(expectedArtist.Id, jsonDocument.RootElement.GetProperty("data").GetProperty("id").GetGuid());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldForwardCancellationTokenToApi()
|
||||
{
|
||||
// Arrange
|
||||
GetMusicArtistViewRequest request = _getMusicArtistViewRequestFixture.Create();
|
||||
using CancellationTokenSource cancellationTokenSource = new();
|
||||
_mockApiHttpClient.GetAsync<MusicArtistDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_musicArtistDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationTokenSource.Token);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<MusicArtistDto>(
|
||||
Arg.Any<string>(),
|
||||
Arg.Is(cancellationTokenSource.Token));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the upstream endpoint the artist retrieval is expected to be sent to.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
|
||||
/// <param name="artistId">The normalized Id of the artist.</param>
|
||||
/// <returns>The expected upstream endpoint.</returns>
|
||||
private static string BuildExpectedEndpoint(Guid libraryId, Guid artistId)
|
||||
{
|
||||
return ApiRoutes.Music.GET_ARTIST
|
||||
.Replace("{libraryId}", libraryId.ToString())
|
||||
.Replace("{artistId}", artistId.ToString());
|
||||
}
|
||||
}
|
||||
+221
@@ -0,0 +1,221 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Common.Enums.Common;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Artists;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetMusicArtists;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Artists;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetMusicArtists;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetMusicArtistsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetMusicArtistsEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly GetMusicArtistsEndpoint _sut;
|
||||
private readonly GetMusicArtistsLiteRequestFixture _getMusicArtistsLiteRequestFixture = new();
|
||||
private readonly PaginatedDtoFixture<MusicArtistLiteDto> _paginatedMusicArtistLiteDtoFixture = new();
|
||||
private readonly MusicArtistLiteDtoFixture _musicArtistLiteDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetMusicArtistsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetMusicArtistsEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<GetMusicArtistsEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalledWithAllParameters_ShouldBuildExactQueryString()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
const string SEARCH_TERM = " The Beatles ";
|
||||
const string FILTER_ALPHA_KEY = "B";
|
||||
const string SORT_BY = "name asc";
|
||||
GetMusicArtistsLiteRequest request = _getMusicArtistsLiteRequestFixture.Create(
|
||||
libraryId: libraryId,
|
||||
currentPage: 2,
|
||||
perPage: 48,
|
||||
searchTerm: SEARCH_TERM,
|
||||
filterAlphaKey: FILTER_ALPHA_KEY,
|
||||
shouldIgnoreThePrefixForAlphaPicker: true,
|
||||
sortBy: SORT_BY,
|
||||
sortOrder: SortOrder.Descending);
|
||||
_mockApiHttpClient.GetAsync<PaginatedDto<MusicArtistLiteDto>>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedMusicArtistLiteDtoFixture.Create());
|
||||
string expectedEndpoint = $"{BuildExpectedEndpoint(libraryId)}?currentPage=2&perPage=48" +
|
||||
$"&searchTerm={Uri.EscapeDataString(SEARCH_TERM)}" +
|
||||
$"&filterAlphaKey={Uri.EscapeDataString(FILTER_ALPHA_KEY)}" +
|
||||
"&shouldIgnoreThePrefixForAlphaPicker=True" +
|
||||
$"&sortBy={Uri.EscapeDataString(SORT_BY)}" +
|
||||
"&sortOrder=Descending";
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedDto<MusicArtistLiteDto>>(
|
||||
Arg.Is<string>(endpoint => endpoint == expectedEndpoint),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOptionalParametersAreOmitted_ShouldAppendOnlyTheIgnorePrefixFlag()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
GetMusicArtistsLiteRequest request = _getMusicArtistsLiteRequestFixture.Create(
|
||||
libraryId: libraryId,
|
||||
includeCurrentPage: false,
|
||||
includePerPage: false,
|
||||
includeSearchTerm: false,
|
||||
includeFilterAlphaKey: false,
|
||||
includeSortBy: false,
|
||||
includeSortOrder: false);
|
||||
_mockApiHttpClient.GetAsync<PaginatedDto<MusicArtistLiteDto>>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedMusicArtistLiteDtoFixture.Create());
|
||||
string expectedEndpoint = $"{BuildExpectedEndpoint(libraryId)}?shouldIgnoreThePrefixForAlphaPicker=False";
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedDto<MusicArtistLiteDto>>(
|
||||
Arg.Is<string>(endpoint => endpoint == expectedEndpoint),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSearchTermHasSpecialCharacters_ShouldEscapeIt()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
const string SEARCH_TERM = "rock & roll";
|
||||
GetMusicArtistsLiteRequest request = _getMusicArtistsLiteRequestFixture.Create(
|
||||
libraryId: libraryId,
|
||||
searchTerm: SEARCH_TERM,
|
||||
includeCurrentPage: false,
|
||||
includePerPage: false,
|
||||
includeFilterAlphaKey: false,
|
||||
includeSortBy: false,
|
||||
includeSortOrder: false);
|
||||
_mockApiHttpClient.GetAsync<PaginatedDto<MusicArtistLiteDto>>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedMusicArtistLiteDtoFixture.Create());
|
||||
string expectedEndpoint = $"{BuildExpectedEndpoint(libraryId)}?searchTerm={Uri.EscapeDataString(SEARCH_TERM)}&shouldIgnoreThePrefixForAlphaPicker=False";
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedDto<MusicArtistLiteDto>>(
|
||||
Arg.Is<string>(endpoint => endpoint == expectedEndpoint),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSearchTermAndAlphaKeyAndSortByAreWhitespace_ShouldOmitThem()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
GetMusicArtistsLiteRequest request = _getMusicArtistsLiteRequestFixture.Create(
|
||||
libraryId: libraryId,
|
||||
searchTerm: " ",
|
||||
filterAlphaKey: " ",
|
||||
sortBy: string.Empty,
|
||||
includeCurrentPage: false,
|
||||
includePerPage: false,
|
||||
includeSortOrder: false);
|
||||
_mockApiHttpClient.GetAsync<PaginatedDto<MusicArtistLiteDto>>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedMusicArtistLiteDtoFixture.Create());
|
||||
string expectedEndpoint = $"{BuildExpectedEndpoint(libraryId)}?shouldIgnoreThePrefixForAlphaPicker=False";
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedDto<MusicArtistLiteDto>>(
|
||||
Arg.Is<string>(endpoint => endpoint == expectedEndpoint),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOnlyCurrentPageIsProvided_ShouldAppendOnlyCurrentPageAndTheIgnorePrefixFlag()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
GetMusicArtistsLiteRequest request = _getMusicArtistsLiteRequestFixture.Create(
|
||||
libraryId: libraryId,
|
||||
currentPage: 3,
|
||||
includePerPage: false,
|
||||
includeSearchTerm: false,
|
||||
includeFilterAlphaKey: false,
|
||||
includeSortBy: false,
|
||||
includeSortOrder: false);
|
||||
_mockApiHttpClient.GetAsync<PaginatedDto<MusicArtistLiteDto>>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedMusicArtistLiteDtoFixture.Create());
|
||||
string expectedEndpoint = $"{BuildExpectedEndpoint(libraryId)}?currentPage=3&shouldIgnoreThePrefixForAlphaPicker=False";
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedDto<MusicArtistLiteDto>>(
|
||||
Arg.Is<string>(endpoint => endpoint == expectedEndpoint),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsPaginatedArtists_ShouldReturnSuccessJsonWithArtists()
|
||||
{
|
||||
// Arrange
|
||||
GetMusicArtistsLiteRequest request = _getMusicArtistsLiteRequestFixture.Create();
|
||||
PaginatedDto<MusicArtistLiteDto> expectedResponse = _paginatedMusicArtistLiteDtoFixture.Create(
|
||||
data: [_musicArtistLiteDtoFixture.Create(name: "Test Artist")],
|
||||
currentPage: 1,
|
||||
perPage: 20,
|
||||
count: 1,
|
||||
numberOfPages: 1);
|
||||
_mockApiHttpClient.GetAsync<PaginatedDto<MusicArtistLiteDto>>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedResponse);
|
||||
|
||||
// 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(1, data.GetProperty("currentPage").GetInt32());
|
||||
Assert.Equal(1, data.GetProperty("data").GetArrayLength());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the upstream endpoint the artist retrieval is expected to be sent to, without query parameters.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library whose artists are retrieved.</param>
|
||||
/// <returns>The expected upstream endpoint.</returns>
|
||||
private static string BuildExpectedEndpoint(Guid libraryId)
|
||||
{
|
||||
return ApiRoutes.Music.GET_ARTISTS_LITE.Replace("{libraryId}", libraryId.ToString());
|
||||
}
|
||||
}
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Common.DTO.Themes;
|
||||
using Lumina.Presentation.Web.Common.Http;
|
||||
using Lumina.Presentation.Web.Common.Primitives;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Common.Services;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.Index;
|
||||
using Lumina.Presentation.Web.Core.Themes;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Artists;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Antiforgery;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using Microsoft.Extensions.Localization;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.Index;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicArtistsIndexViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicArtistsIndexViewEndpointTests
|
||||
{
|
||||
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 MusicArtistsIndexViewEndpoint _sut;
|
||||
private readonly LibraryDtoFixture _libraryDtoFixture = new();
|
||||
private readonly GetMusicArtistsViewRequestFixture _getMusicArtistsViewRequestFixture = new();
|
||||
private readonly ThemePageRenderResultDtoFixture _themePageRenderResultDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MusicArtistsIndexViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public MusicArtistsIndexViewEndpointTests()
|
||||
{
|
||||
_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.GetAllStrings(Arg.Any<bool>()).Returns(new LocalizedString[] { new("Search", "Search") });
|
||||
_mockStringLocalizerFactory = Substitute.For<IStringLocalizerFactory>();
|
||||
_mockStringLocalizerFactory.Create(Arg.Any<string>(), Arg.Any<string>()).Returns(_mockStringLocalizer);
|
||||
_sut = Factory.Create<MusicArtistsIndexViewEndpoint>(_mockApiHttpClient, _mockUrlService, _mockThemePageRenderer, _mockAntiforgery, _mockStringLocalizerFactory);
|
||||
TestHttpContextFactory.ConfigureSession(_sut.HttpContext, TestHttpContextFactory.CreateSession());
|
||||
_sut.HttpContext.Request.Path = "/en-us/library/audio-library/music-library/artists";
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenLibraryIdIsNull_ShouldRedirectToHome()
|
||||
{
|
||||
// Arrange
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Home.INDEX_CULTURED).Returns("http://localhost/en-us");
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(_getMusicArtistsViewRequestFixture.Create(libraryId: null), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
RedirectHttpResult redirectResult = Assert.IsType<RedirectHttpResult>(result);
|
||||
Assert.Equal("http://localhost/en-us", redirectResult.Url);
|
||||
await _mockApiHttpClient.DidNotReceive().GetAsync<LibraryDto>(Arg.Any<string>(), Arg.Any<CancellationToken>());
|
||||
await _mockThemePageRenderer.DidNotReceive().RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
|
||||
_mockAntiforgery.DidNotReceive().GetAndStoreTokens(Arg.Any<HttpContext>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenLibraryIdProvided_ShouldRenderThemedPageThroughTheSharedView()
|
||||
{
|
||||
// Arrange
|
||||
LibraryDto expectedLibrary = _libraryDtoFixture.Create();
|
||||
_mockApiHttpClient.GetAsync<LibraryDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedLibrary);
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Music.GET_ARTISTS).Returns("http://localhost/en-us/library/audio-library/music-library/artists/api-get-artists");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Settings.GET_USER_SETTINGS).Returns("http://localhost/en-us/tools/settings/api-get-user-settings");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Music.ARTIST, Arg.Any<object>()).Returns("http://localhost/en-us/library/audio-library/music-library/artists/00000000-0000-0000-0000-000000000000");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Music.DELETE_ARTIST, Arg.Any<object>()).Returns("http://localhost/en-us/library/audio-library/music-library/artists/00000000-0000-0000-0000-000000000000/api-delete-artist");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Music.DELETED_MUSIC_ITEMS).Returns("http://localhost/en-us/library/audio-library/music-library/deleted-items");
|
||||
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_themePageRenderResultDtoFixture.Create(content: "<section>content</section>", script: "<script>script</script>")));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(_getMusicArtistsViewRequestFixture.Create(libraryId: expectedLibrary.Id), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.IsType<RazorViewResult>(result);
|
||||
await _mockApiHttpClient.Received(1).GetAsync<LibraryDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Libraries.GET_LIBRARY_BY_ID.Replace("{id}", expectedLibrary.Id.ToString())),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockThemePageRenderer.Received(1).RenderAsync(
|
||||
Arg.Is<ThemePageDto>(page =>
|
||||
page.PageKey == "library/audio-library/music-library/artists/index" &&
|
||||
page.Title == expectedLibrary.Title &&
|
||||
page.PageData.ContainsKey("libraryId") &&
|
||||
page.PageData.ContainsKey("settingsUrl") &&
|
||||
page.PageData.ContainsKey("strings") &&
|
||||
string.Equals(
|
||||
page.PageData["itemsUrl"] as string,
|
||||
"http://localhost/en-us/library/audio-library/music-library/artists/api-get-artists",
|
||||
StringComparison.Ordinal) &&
|
||||
string.Equals(
|
||||
page.PageData["artistUrl"] as string,
|
||||
"http://localhost/en-us/library/audio-library/music-library/artists/00000000-0000-0000-0000-000000000000",
|
||||
StringComparison.Ordinal) &&
|
||||
string.Equals(
|
||||
page.PageData["deleteUrl"] as string,
|
||||
"http://localhost/en-us/library/audio-library/music-library/artists/00000000-0000-0000-0000-000000000000/api-delete-artist",
|
||||
StringComparison.Ordinal) &&
|
||||
string.Equals(
|
||||
page.PageData["deletedItemsUrl"] as string,
|
||||
"http://localhost/en-us/library/audio-library/music-library/deleted-items",
|
||||
StringComparison.Ordinal)),
|
||||
Arg.Is<string?>(requestedThemeId => requestedThemeId == null),
|
||||
Arg.Any<CancellationToken>());
|
||||
_mockAntiforgery.Received(1).GetAndStoreTokens(Arg.Any<HttpContext>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenThemeRenderingFails_ShouldFallBackToRazorView()
|
||||
{
|
||||
// Arrange
|
||||
LibraryDto expectedLibrary = _libraryDtoFixture.Create();
|
||||
_mockApiHttpClient.GetAsync<LibraryDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedLibrary);
|
||||
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result<ThemePageRenderResultDto>.Failure(Error.Failure("Theme.Render", "The page could not be rendered.")));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(_getMusicArtistsViewRequestFixture.Create(libraryId: expectedLibrary.Id), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.IsType<RazorViewResult>(result);
|
||||
await _mockThemePageRenderer.Received(1).RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+168
@@ -0,0 +1,168 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.RestoreMusicArtist;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.RestoreMusicArtist;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="RestoreMusicArtistEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RestoreMusicArtistEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly RestoreMusicArtistEndpoint _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RestoreMusicArtistEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public RestoreMusicArtistEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<RestoreMusicArtistEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("D")] // Standard hyphenated format.
|
||||
[InlineData("B")] // Braced format.
|
||||
[InlineData("N")] // Compact format.
|
||||
[InlineData("P")] // Parenthesized format.
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldRestoreArtistViaApiWithNormalizedIdsAndReturnSuccessPayload(string guidFormat)
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ConfigureRequest(artistId.ToString(guidFormat), libraryId.ToString(guidFormat));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync(
|
||||
BuildExpectedEndpoint(libraryId, artistId),
|
||||
Arg.Any<CancellationToken>());
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("data").GetProperty("isRestored").GetBoolean());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenArtistRouteIdIsNotParseable_ShouldForwardGuidEmptyArtistIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ConfigureRequest("not-a-guid", libraryId.ToString());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync(
|
||||
BuildExpectedEndpoint(libraryId, Guid.Empty),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenArtistRouteIdIsMissing_ShouldForwardGuidEmptyArtistIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ConfigureRequest(null, libraryId.ToString());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync(
|
||||
BuildExpectedEndpoint(libraryId, Guid.Empty),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenLibraryQueryIdIsNotParseable_ShouldForwardGuidEmptyLibraryIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
ConfigureRequest(artistId.ToString(), "not-a-guid");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync(
|
||||
BuildExpectedEndpoint(Guid.Empty, artistId),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenLibraryQueryIdIsMissing_ShouldForwardGuidEmptyLibraryIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
ConfigureRequest(artistId.ToString(), null);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync(
|
||||
BuildExpectedEndpoint(Guid.Empty, artistId),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ConfigureRequest(artistId.ToString(), libraryId.ToString());
|
||||
using CancellationTokenSource cancellationTokenSource = new();
|
||||
cancellationTokenSource.Cancel();
|
||||
_mockApiHttpClient.PostIgnoringResponseAsync(
|
||||
Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromCanceled(cancellationTokenSource.Token));
|
||||
|
||||
// Act & Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(
|
||||
() => _sut.ExecuteAsync(EmptyRequest.Instance, cancellationTokenSource.Token));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the route and query values the endpoint reads the artist identity from.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The raw route value of the artist Id, or <see langword="null"/> to leave the route value missing.</param>
|
||||
/// <param name="libraryId">The raw query value of the library Id, or <see langword="null"/> to leave the query string missing.</param>
|
||||
private void ConfigureRequest(string? artistId, string? libraryId)
|
||||
{
|
||||
if (artistId is not null)
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = artistId;
|
||||
if (libraryId is not null)
|
||||
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={libraryId}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the upstream endpoint the artist restoration is expected to be sent to.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The normalized Id of the media library.</param>
|
||||
/// <param name="artistId">The normalized Id of the artist.</param>
|
||||
/// <returns>The expected upstream endpoint.</returns>
|
||||
private static string BuildExpectedEndpoint(Guid libraryId, Guid artistId)
|
||||
{
|
||||
return ApiRoutes.Music.RESTORE_ARTIST
|
||||
.Replace("{libraryId}", libraryId.ToString())
|
||||
.Replace("{artistId}", artistId.ToString());
|
||||
}
|
||||
}
|
||||
+181
@@ -0,0 +1,181 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Artists;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.SaveMusicArtist;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Artists;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.SaveMusicArtist;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="SaveMusicArtistEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SaveMusicArtistEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly SaveMusicArtistEndpoint _sut;
|
||||
private readonly UpdateMusicArtistRequestFixture _updateMusicArtistRequestFixture = new();
|
||||
private readonly MusicArtistDtoFixture _musicArtistDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SaveMusicArtistEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public SaveMusicArtistEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<SaveMusicArtistEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldForwardUpdateMusicArtistRequestToApiWithRouteAndQueryIds()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
UpdateMusicArtistRequest request = _updateMusicArtistRequestFixture.Create();
|
||||
MusicArtistDto expectedArtist = _musicArtistDtoFixture.Create();
|
||||
_mockApiHttpClient.PutAsync<MusicArtistDto, UpdateMusicArtistRequest>(Arg.Any<string>(), Arg.Any<UpdateMusicArtistRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedArtist);
|
||||
ConfigureRequest(artistId.ToString(), libraryId);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutAsync<MusicArtistDto, UpdateMusicArtistRequest>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(libraryId, artistId)),
|
||||
Arg.Is<UpdateMusicArtistRequest>(forwardedRequest => forwardedRequest == request),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenArtistRouteIdIsNotParseable_ShouldForwardGuidEmptyArtistIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
const string MALICIOUS_ARTIST_ID = "not-a-guid";
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
UpdateMusicArtistRequest request = _updateMusicArtistRequestFixture.Create();
|
||||
_mockApiHttpClient.PutAsync<MusicArtistDto, UpdateMusicArtistRequest>(Arg.Any<string>(), Arg.Any<UpdateMusicArtistRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_musicArtistDtoFixture.Create());
|
||||
ConfigureRequest(MALICIOUS_ARTIST_ID, libraryId);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutAsync<MusicArtistDto, UpdateMusicArtistRequest>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(libraryId, Guid.Empty)),
|
||||
Arg.Any<UpdateMusicArtistRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenArtistRouteIdIsMissing_ShouldForwardGuidEmptyArtistIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
UpdateMusicArtistRequest request = _updateMusicArtistRequestFixture.Create();
|
||||
_mockApiHttpClient.PutAsync<MusicArtistDto, UpdateMusicArtistRequest>(Arg.Any<string>(), Arg.Any<UpdateMusicArtistRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_musicArtistDtoFixture.Create());
|
||||
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={libraryId}");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutAsync<MusicArtistDto, UpdateMusicArtistRequest>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(libraryId, Guid.Empty)),
|
||||
Arg.Any<UpdateMusicArtistRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenLibraryQueryIdIsNotParseable_ShouldForwardGuidEmptyLibraryIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
const string MALICIOUS_LIBRARY_ID = "not-a-guid";
|
||||
UpdateMusicArtistRequest request = _updateMusicArtistRequestFixture.Create();
|
||||
_mockApiHttpClient.PutAsync<MusicArtistDto, UpdateMusicArtistRequest>(Arg.Any<string>(), Arg.Any<UpdateMusicArtistRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_musicArtistDtoFixture.Create());
|
||||
ConfigureRequest(artistId.ToString(), MALICIOUS_LIBRARY_ID);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutAsync<MusicArtistDto, UpdateMusicArtistRequest>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(Guid.Empty, artistId)),
|
||||
Arg.Any<UpdateMusicArtistRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsUpdatedArtist_ShouldReturnSuccessJsonWithArtist()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
UpdateMusicArtistRequest request = _updateMusicArtistRequestFixture.Create();
|
||||
MusicArtistDto expectedArtist = _musicArtistDtoFixture.Create();
|
||||
_mockApiHttpClient.PutAsync<MusicArtistDto, UpdateMusicArtistRequest>(Arg.Any<string>(), Arg.Any<UpdateMusicArtistRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedArtist);
|
||||
ConfigureRequest(artistId.ToString(), libraryId);
|
||||
|
||||
// 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());
|
||||
Assert.Equal(expectedArtist.Id, jsonDocument.RootElement.GetProperty("data").GetProperty("id").GetGuid());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the route and query values the endpoint reads the artist identities from.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The raw route value of the artist Id.</param>
|
||||
/// <param name="libraryId">The raw query value of the library Id.</param>
|
||||
private void ConfigureRequest(string artistId, Guid libraryId)
|
||||
{
|
||||
ConfigureRequest(artistId, libraryId.ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the route and query values the endpoint reads the artist identities from.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The raw route value of the artist Id.</param>
|
||||
/// <param name="libraryId">The raw query value of the library Id.</param>
|
||||
private void ConfigureRequest(string artistId, string libraryId)
|
||||
{
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = artistId;
|
||||
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={libraryId}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the upstream endpoint the artist update is expected to be sent to.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The normalized Id of the media library.</param>
|
||||
/// <param name="artistId">The normalized Id of the artist.</param>
|
||||
/// <returns>The expected upstream endpoint.</returns>
|
||||
private static string BuildExpectedEndpoint(Guid libraryId, Guid artistId)
|
||||
{
|
||||
return ApiRoutes.Music.UPDATE_ARTIST
|
||||
.Replace("{libraryId}", libraryId.ToString())
|
||||
.Replace("{artistId}", artistId.ToString());
|
||||
}
|
||||
}
|
||||
+297
@@ -0,0 +1,297 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.UpdateArtistCover;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.Features;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.UpdateArtistCover;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="UpdateArtistCoverEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateArtistCoverEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly UpdateArtistCoverEndpoint _sut;
|
||||
private readonly UpdateMusicCoverDtoFixture _updateMusicCoverDtoFixture = new();
|
||||
private static readonly Guid s_libraryId = Guid.NewGuid();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateArtistCoverEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public UpdateArtistCoverEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<UpdateArtistCoverEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalledWithFile_ShouldUploadCoverToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
_mockApiHttpClient.PutMultipartAsync<UpdateMusicCoverDto>(Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_updateMusicCoverDtoFixture.Create(coverPath: "/media/artists/cover.jpg"));
|
||||
ConfigureRequest(artistId, [1, 2, 3], "cover.jpg");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutMultipartAsync<UpdateMusicCoverDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(s_libraryId.ToString(), artistId)),
|
||||
Arg.Any<Stream>(),
|
||||
Arg.Is<string>(fileName => fileName == "cover.jpg"),
|
||||
Arg.Is<string>(fieldName => fieldName == "cover"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenArtistRouteIdIsNotParseable_ShouldUploadCoverWithEmptyId()
|
||||
{
|
||||
// Arrange
|
||||
const string MALICIOUS_ARTIST_ID = "not-a-guid";
|
||||
_mockApiHttpClient.PutMultipartAsync<UpdateMusicCoverDto>(Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_updateMusicCoverDtoFixture.Create(coverPath: "/media/artists/cover.jpg"));
|
||||
ConfigureRequest(MALICIOUS_ARTIST_ID, [1, 2, 3], "cover.jpg");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutMultipartAsync<UpdateMusicCoverDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(s_libraryId.ToString(), Guid.Empty)),
|
||||
Arg.Any<Stream>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenLibraryQueryIdIsNotParseable_ShouldUploadCoverWithEmptyLibraryId()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
_mockApiHttpClient.PutMultipartAsync<UpdateMusicCoverDto>(Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_updateMusicCoverDtoFixture.Create(coverPath: "/media/artists/cover.jpg"));
|
||||
ConfigureRequest(artistId, [1, 2, 3], "cover.jpg");
|
||||
// The query value is normalized to a Guid before it is substituted into the upstream URL, so a crafted value can never escape its segment.
|
||||
_sut.HttpContext.Request.QueryString = new QueryString("?libraryId=not-a-library-guid");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutMultipartAsync<UpdateMusicCoverDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(Guid.Empty.ToString(), artistId)),
|
||||
Arg.Any<Stream>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenLibraryQueryIdIsMissing_ShouldUploadCoverWithEmptyLibraryId()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
_mockApiHttpClient.PutMultipartAsync<UpdateMusicCoverDto>(Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_updateMusicCoverDtoFixture.Create(coverPath: "/media/artists/cover.jpg"));
|
||||
ConfigureRequest(artistId, [1, 2, 3], "cover.jpg");
|
||||
_sut.HttpContext.Request.QueryString = new QueryString(string.Empty);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutMultipartAsync<UpdateMusicCoverDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(Guid.Empty.ToString(), artistId)),
|
||||
Arg.Any<Stream>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsCoverPath_ShouldReturnSuccessJsonWithPath()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
const string EXPECTED_PATH = "/media/artists/cover.jpg";
|
||||
_mockApiHttpClient.PutMultipartAsync<UpdateMusicCoverDto>(Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_updateMusicCoverDtoFixture.Create(coverPath: EXPECTED_PATH));
|
||||
ConfigureRequest(artistId, [1, 2, 3], "cover.jpg");
|
||||
|
||||
// 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.Equal(EXPECTED_PATH, jsonDocument.RootElement.GetProperty("data").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenFormHasNoFile_ShouldForwardRequestWithoutFileToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
const string EXPECTED_PATH = "/media/artists/cover.jpg";
|
||||
_mockApiHttpClient.PutMultipartAsync<UpdateMusicCoverDto>(Arg.Any<string>(), Arg.Any<Stream?>(), Arg.Any<string?>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_updateMusicCoverDtoFixture.Create(coverPath: EXPECTED_PATH));
|
||||
ConfigureRequestWithoutFiles(artistId);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutMultipartAsync<UpdateMusicCoverDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(s_libraryId.ToString(), artistId)),
|
||||
Arg.Is<Stream?>(stream => stream == null),
|
||||
Arg.Is<string?>(fileName => fileName == null),
|
||||
Arg.Is<string>(fieldName => fieldName == "cover"),
|
||||
Arg.Any<CancellationToken>());
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(EXPECTED_PATH, jsonDocument.RootElement.GetProperty("data").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRequestIsNotMultipart_ShouldForwardRequestWithoutFileToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
const string EXPECTED_PATH = "/media/artists/cover.jpg";
|
||||
_mockApiHttpClient.PutMultipartAsync<UpdateMusicCoverDto>(Arg.Any<string>(), Arg.Any<Stream?>(), Arg.Any<string?>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_updateMusicCoverDtoFixture.Create(coverPath: EXPECTED_PATH));
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
|
||||
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={s_libraryId}");
|
||||
_sut.HttpContext.Request.ContentType = "application/json";
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutMultipartAsync<UpdateMusicCoverDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(s_libraryId.ToString(), artistId)),
|
||||
Arg.Is<Stream?>(stream => stream == null),
|
||||
Arg.Is<string?>(fileName => fileName == null),
|
||||
Arg.Is<string>(fieldName => fieldName == "cover"),
|
||||
Arg.Any<CancellationToken>());
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(EXPECTED_PATH, jsonDocument.RootElement.GetProperty("data").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenFormIsMalformed_ShouldForwardRequestWithoutFileToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
const string EXPECTED_PATH = "/media/artists/cover.jpg";
|
||||
_mockApiHttpClient.PutMultipartAsync<UpdateMusicCoverDto>(Arg.Any<string>(), Arg.Any<Stream?>(), Arg.Any<string?>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_updateMusicCoverDtoFixture.Create(coverPath: EXPECTED_PATH));
|
||||
ConfigureMalformedRequest(artistId);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutMultipartAsync<UpdateMusicCoverDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(s_libraryId.ToString(), artistId)),
|
||||
Arg.Is<Stream?>(stream => stream == null),
|
||||
Arg.Is<string?>(fileName => fileName == null),
|
||||
Arg.Is<string>(fieldName => fieldName == "cover"),
|
||||
Arg.Any<CancellationToken>());
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(EXPECTED_PATH, jsonDocument.RootElement.GetProperty("data").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures a multipart form request carrying a single file.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The route Id of the artist whose cover is uploaded.</param>
|
||||
/// <param name="content">The bytes of the uploaded file.</param>
|
||||
/// <param name="fileName">The name of the uploaded file.</param>
|
||||
private void ConfigureRequest(Guid artistId, byte[] content, string fileName)
|
||||
{
|
||||
ConfigureRequest(artistId.ToString(), content, fileName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures a multipart form request carrying a single file.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The raw route value of the artist Id.</param>
|
||||
/// <param name="content">The bytes of the uploaded file.</param>
|
||||
/// <param name="fileName">The name of the uploaded file.</param>
|
||||
private void ConfigureRequest(string artistId, byte[] content, string fileName)
|
||||
{
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = artistId;
|
||||
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={s_libraryId}");
|
||||
MemoryStream coverStream = new(content);
|
||||
IFormFile formFile = new FormFile(coverStream, 0, content.Length, "cover", fileName);
|
||||
FormFileCollection files = [formFile];
|
||||
IFormCollection form = new FormCollection([], files);
|
||||
_sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test";
|
||||
_sut.HttpContext.Features.Set<IFormFeature>(new FormFeature(form));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures a multipart form request without any file.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The route Id of the artist whose cover is uploaded.</param>
|
||||
private void ConfigureRequestWithoutFiles(Guid artistId)
|
||||
{
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
|
||||
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={s_libraryId}");
|
||||
IFormCollection form = new FormCollection([]);
|
||||
_sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test";
|
||||
_sut.HttpContext.Features.Set<IFormFeature>(new FormFeature(form));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures a multipart form request whose body cannot be parsed.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The route Id of the artist whose cover is uploaded.</param>
|
||||
private void ConfigureMalformedRequest(Guid artistId)
|
||||
{
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
|
||||
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={s_libraryId}");
|
||||
_sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test";
|
||||
IFormCollection malformedForm = Substitute.For<IFormCollection>();
|
||||
malformedForm.Files.Returns(_ => throw new InvalidDataException("Malformed multipart body."));
|
||||
_sut.HttpContext.Features.Set<IFormFeature>(new FormFeature(malformedForm));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the upstream endpoint the cover upload is expected to be sent to.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The raw Id of the media library.</param>
|
||||
/// <param name="artistId">The normalized Id of the artist.</param>
|
||||
/// <returns>The expected upstream endpoint.</returns>
|
||||
private static string BuildExpectedEndpoint(string libraryId, Guid artistId)
|
||||
{
|
||||
return ApiRoutes.Music.UPDATE_ARTIST_COVER
|
||||
.Replace("{libraryId}", libraryId)
|
||||
.Replace("{artistId}", artistId.ToString());
|
||||
}
|
||||
}
|
||||
+345
@@ -0,0 +1,345 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Common.DTO.Themes;
|
||||
using Lumina.Presentation.Web.Common.Http;
|
||||
using Lumina.Presentation.Web.Common.Primitives;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Common.Services;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.DeletedMusicItems;
|
||||
using Lumina.Presentation.Web.Core.Themes;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Artists;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Antiforgery;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using Microsoft.Extensions.Localization;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Reflection;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.DeletedMusicItems;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="DeletedMusicItemsViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeletedMusicItemsViewEndpointTests
|
||||
{
|
||||
private const string ZERO_GUID = "00000000-0000-0000-0000-000000000000";
|
||||
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly IUrlService _mockUrlService;
|
||||
private readonly ThemePageRenderer _mockThemePageRenderer;
|
||||
private readonly IAntiforgery _mockAntiforgery;
|
||||
private readonly IStringLocalizerFactory _mockStringLocalizerFactory;
|
||||
private readonly IStringLocalizer _mockStringLocalizer;
|
||||
private readonly DeletedMusicItemsViewEndpoint _sut;
|
||||
private readonly LibraryDtoFixture _libraryDtoFixture = new();
|
||||
private readonly DeletedMusicArtistDtoFixture _deletedMusicArtistDtoFixture = new();
|
||||
private readonly DeletedMusicAlbumDtoFixture _deletedMusicAlbumDtoFixture = new();
|
||||
private readonly DeletedMusicTrackDtoFixture _deletedMusicTrackDtoFixture = new();
|
||||
private readonly DeletedMusicItemsPageDtoFixture _deletedMusicItemsPageDtoFixture = new();
|
||||
private readonly GetMusicArtistsViewRequestFixture _getMusicArtistsViewRequestFixture = new();
|
||||
private readonly ThemePageRenderResultDtoFixture _themePageRenderResultDtoFixture = new();
|
||||
private readonly List<object?> _artistRestoreRouteValues = [];
|
||||
private readonly List<object?> _albumRestoreRouteValues = [];
|
||||
private readonly List<object?> _trackRestoreRouteValues = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeletedMusicItemsViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public DeletedMusicItemsViewEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_mockUrlService = Substitute.For<IUrlService>();
|
||||
_mockThemePageRenderer = Substitute.For<ThemePageRenderer>(new ThemeService(_mockApiHttpClient), new ThemeTemplateEngine());
|
||||
_mockAntiforgery = Substitute.For<IAntiforgery>();
|
||||
_mockAntiforgery.GetAndStoreTokens(Arg.Any<HttpContext>())
|
||||
.Returns(new AntiforgeryTokenSet("request-token", "cookie-token", "__RequestVerificationToken", "RequestVerificationToken"));
|
||||
_mockStringLocalizer = Substitute.For<IStringLocalizer>();
|
||||
_mockStringLocalizer[Arg.Any<string>()].Returns(callInfo => new LocalizedString(
|
||||
callInfo.Arg<string>(),
|
||||
callInfo.Arg<string>() == "Title" ? "Deleted items" : $"Localized-{callInfo.Arg<string>()}"));
|
||||
_mockStringLocalizer.GetAllStrings(Arg.Any<bool>()).Returns(
|
||||
[
|
||||
new("Title", "Deleted items"),
|
||||
new("BackToLibrary", "Back to library"),
|
||||
new("NoDeletedItems", "There are no deleted items in this library."),
|
||||
new("Artists", "Artists"),
|
||||
new("Albums", "Albums"),
|
||||
new("Tracks", "Tracks"),
|
||||
new("Name", "Name"),
|
||||
new("Artist", "Artist"),
|
||||
new("Album", "Album"),
|
||||
new("TrackTitle", "Title"),
|
||||
new("DeletedOn", "Deleted on"),
|
||||
new("Restore", "Restore"),
|
||||
new("Restored", "The item was restored."),
|
||||
new("RestoreFailed", "The item could not be restored.")
|
||||
]);
|
||||
_mockStringLocalizerFactory = Substitute.For<IStringLocalizerFactory>();
|
||||
_mockStringLocalizerFactory.Create(Arg.Any<string>(), Arg.Any<string>()).Returns(_mockStringLocalizer);
|
||||
_sut = Factory.Create<DeletedMusicItemsViewEndpoint>(_mockApiHttpClient, _mockUrlService, _mockThemePageRenderer, _mockAntiforgery, _mockStringLocalizerFactory);
|
||||
TestHttpContextFactory.ConfigureSession(_sut.HttpContext, TestHttpContextFactory.CreateSession());
|
||||
_sut.HttpContext.Request.Path = "/en-us/library/audio-library/music-library/deleted-items";
|
||||
|
||||
StubUrls();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenThemeRenderingSucceeds_ShouldRenderThemedViewWithDocumentedPageData()
|
||||
{
|
||||
// Arrange
|
||||
LibraryDto library = _libraryDtoFixture.Create(title: "Music");
|
||||
DeletedMusicArtistDto[] deletedArtists = [.. _deletedMusicArtistDtoFixture.CreateMany(2)];
|
||||
DeletedMusicAlbumDto[] deletedAlbums = [.. _deletedMusicAlbumDtoFixture.CreateMany(2)];
|
||||
DeletedMusicTrackDto[] deletedTracks = [.. _deletedMusicTrackDtoFixture.CreateMany(2)];
|
||||
Guid libraryId = library.Id!.Value;
|
||||
_mockApiHttpClient.GetAsync<LibraryDto>(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(library);
|
||||
_mockApiHttpClient.GetAsync<DeletedMusicArtistDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(deletedArtists);
|
||||
_mockApiHttpClient.GetAsync<DeletedMusicAlbumDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(deletedAlbums);
|
||||
_mockApiHttpClient.GetAsync<DeletedMusicTrackDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(deletedTracks);
|
||||
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_themePageRenderResultDtoFixture.Create(content: "<section>deleted</section>", script: "<script>deleted</script>")));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(_getMusicArtistsViewRequestFixture.Create(libraryId: libraryId), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("/Core/Views/Shared/_ThemedView.cshtml", GetRenderedViewName(result));
|
||||
await _mockApiHttpClient.Received(1).GetAsync<LibraryDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Libraries.GET_LIBRARY_BY_ID.Replace("{id}", libraryId.ToString())),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockApiHttpClient.Received(1).GetAsync<DeletedMusicArtistDto[]>(
|
||||
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Music.GET_DELETED_ARTISTS.Replace("{libraryId}", libraryId.ToString())),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockApiHttpClient.Received(1).GetAsync<DeletedMusicAlbumDto[]>(
|
||||
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Music.GET_DELETED_ALBUMS.Replace("{libraryId}", libraryId.ToString())),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockApiHttpClient.Received(1).GetAsync<DeletedMusicTrackDto[]>(
|
||||
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Music.GET_DELETED_TRACKS.Replace("{libraryId}", libraryId.ToString())),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockThemePageRenderer.Received(1).RenderAsync(
|
||||
Arg.Is<ThemePageDto>(page =>
|
||||
page.PageKey == "library/audio-library/music-library/deleted-items" &&
|
||||
page.Title == "Deleted items" &&
|
||||
page.Description == string.Empty &&
|
||||
string.Equals(page.PageData["libraryId"] as string, libraryId.ToString(), StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["libraryTitle"] as string, "Music", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["artistRestoreUrl"] as string, $"http://localhost/en-us/library/audio-library/music-library/artists/{ZERO_GUID}/api-restore-artist", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["albumRestoreUrl"] as string, $"http://localhost/en-us/library/audio-library/music-library/artists/{ZERO_GUID}/albums/{ZERO_GUID}/api-restore-album", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["trackRestoreUrl"] as string, $"http://localhost/en-us/library/audio-library/music-library/artists/{ZERO_GUID}/albums/{ZERO_GUID}/tracks/{ZERO_GUID}/api-restore-track", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["backUrl"] as string, $"http://localhost/en-us/library/audio-library/music-library/artists?libraryId={libraryId}", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["antiforgeryToken"] as string, "request-token", StringComparison.Ordinal) &&
|
||||
HasDocumentedDeletedMusicItems(page, deletedArtists, deletedAlbums, deletedTracks) &&
|
||||
HasDocumentedLocalizedStrings(page)),
|
||||
Arg.Is<string?>(requestedThemeId => requestedThemeId == null),
|
||||
Arg.Any<CancellationToken>());
|
||||
_mockAntiforgery.Received(1).GetAndStoreTokens(_sut.HttpContext);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenLibraryIdIsNull_ShouldRedirectToHome()
|
||||
{
|
||||
// Arrange
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Home.INDEX_CULTURED).Returns("http://localhost/en-us");
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(_getMusicArtistsViewRequestFixture.Create(libraryId: null), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
RedirectHttpResult redirectResult = Assert.IsType<RedirectHttpResult>(result);
|
||||
Assert.Equal("http://localhost/en-us", redirectResult.Url);
|
||||
await _mockApiHttpClient.DidNotReceive().GetAsync<LibraryDto>(Arg.Any<string>(), Arg.Any<CancellationToken>());
|
||||
await _mockApiHttpClient.DidNotReceive().GetAsync<DeletedMusicArtistDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>());
|
||||
await _mockApiHttpClient.DidNotReceive().GetAsync<DeletedMusicAlbumDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>());
|
||||
await _mockApiHttpClient.DidNotReceive().GetAsync<DeletedMusicTrackDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>());
|
||||
await _mockThemePageRenderer.DidNotReceive().RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
|
||||
_mockAntiforgery.DidNotReceive().GetAndStoreTokens(Arg.Any<HttpContext>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenThemeRenderingFails_ShouldFallBackToTheRazorViewWithTheDeletedMusicItems()
|
||||
{
|
||||
// Arrange
|
||||
LibraryDto library = _libraryDtoFixture.Create(title: "Music");
|
||||
DeletedMusicArtistDto[] deletedArtists = [.. _deletedMusicArtistDtoFixture.CreateMany(2)];
|
||||
DeletedMusicAlbumDto[] deletedAlbums = [.. _deletedMusicAlbumDtoFixture.CreateMany(2)];
|
||||
DeletedMusicTrackDto[] deletedTracks = [.. _deletedMusicTrackDtoFixture.CreateMany(2)];
|
||||
_mockApiHttpClient.GetAsync<LibraryDto>(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(library);
|
||||
_mockApiHttpClient.GetAsync<DeletedMusicArtistDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(deletedArtists);
|
||||
_mockApiHttpClient.GetAsync<DeletedMusicAlbumDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(deletedAlbums);
|
||||
_mockApiHttpClient.GetAsync<DeletedMusicTrackDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(deletedTracks);
|
||||
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result<ThemePageRenderResultDto>.Failure(Error.Failure("Theme.Render", "The page could not be rendered.")));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(_getMusicArtistsViewRequestFixture.Create(libraryId: library.Id), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("/Core/Views/Library/AudioLibrary/MusicLibrary/DeletedItems.cshtml", GetRenderedViewName(result));
|
||||
DeletedMusicItemsPageDto expectedPage = _deletedMusicItemsPageDtoFixture.Create(
|
||||
library: library,
|
||||
deletedArtists: deletedArtists,
|
||||
deletedAlbums: deletedAlbums,
|
||||
deletedTracks: deletedTracks);
|
||||
DeletedMusicItemsPageDto model = Assert.IsType<DeletedMusicItemsPageDto>(GetRenderedModel(result));
|
||||
Assert.Equal(expectedPage, model);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldUseTheAllZeroGuidTemplatesOfTheRestoreRoutes()
|
||||
{
|
||||
// Arrange
|
||||
LibraryDto library = _libraryDtoFixture.Create(title: "Music");
|
||||
_mockApiHttpClient.GetAsync<LibraryDto>(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(library);
|
||||
_mockApiHttpClient.GetAsync<DeletedMusicArtistDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(Array.Empty<DeletedMusicArtistDto>());
|
||||
_mockApiHttpClient.GetAsync<DeletedMusicAlbumDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(Array.Empty<DeletedMusicAlbumDto>());
|
||||
_mockApiHttpClient.GetAsync<DeletedMusicTrackDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(Array.Empty<DeletedMusicTrackDto>());
|
||||
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_themePageRenderResultDtoFixture.Create()));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(_getMusicArtistsViewRequestFixture.Create(libraryId: library.Id), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// The themed page replaces each all-zero Guid placeholder of the restore URLs one at a time, so every route value must be an empty Guid.
|
||||
Assert.Single(_artistRestoreRouteValues);
|
||||
AssertRouteValueIsEmptyGuid(_artistRestoreRouteValues[0], "artistId");
|
||||
Assert.Single(_albumRestoreRouteValues);
|
||||
AssertRouteValueIsEmptyGuid(_albumRestoreRouteValues[0], "artistId");
|
||||
AssertRouteValueIsEmptyGuid(_albumRestoreRouteValues[0], "albumId");
|
||||
Assert.Single(_trackRestoreRouteValues);
|
||||
AssertRouteValueIsEmptyGuid(_trackRestoreRouteValues[0], "artistId");
|
||||
AssertRouteValueIsEmptyGuid(_trackRestoreRouteValues[0], "albumId");
|
||||
AssertRouteValueIsEmptyGuid(_trackRestoreRouteValues[0], "trackId");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the absolute URLs that the endpoint resolves for the deleted music items page.
|
||||
/// </summary>
|
||||
private void StubUrls()
|
||||
{
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Music.ARTISTS_INDEX).Returns("http://localhost/en-us/library/audio-library/music-library/artists");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Music.RESTORE_ARTIST, Arg.Any<object?>())
|
||||
.Returns(callInfo =>
|
||||
{
|
||||
_artistRestoreRouteValues.Add(callInfo.ArgAt<object?>(1));
|
||||
return $"http://localhost/en-us/library/audio-library/music-library/artists/{ZERO_GUID}/api-restore-artist";
|
||||
});
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Music.RESTORE_ALBUM, Arg.Any<object?>())
|
||||
.Returns(callInfo =>
|
||||
{
|
||||
_albumRestoreRouteValues.Add(callInfo.ArgAt<object?>(1));
|
||||
return $"http://localhost/en-us/library/audio-library/music-library/artists/{ZERO_GUID}/albums/{ZERO_GUID}/api-restore-album";
|
||||
});
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Music.RESTORE_TRACK, Arg.Any<object?>())
|
||||
.Returns(callInfo =>
|
||||
{
|
||||
_trackRestoreRouteValues.Add(callInfo.ArgAt<object?>(1));
|
||||
return $"http://localhost/en-us/library/audio-library/music-library/artists/{ZERO_GUID}/albums/{ZERO_GUID}/tracks/{ZERO_GUID}/api-restore-track";
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the private view name of the rendered <see cref="RazorViewResult"/>, which the result does not expose publicly.
|
||||
/// </summary>
|
||||
/// <param name="result">The result returned by the endpoint under test.</param>
|
||||
/// <returns>The name or path of the rendered view.</returns>
|
||||
private static string GetRenderedViewName(IResult result)
|
||||
{
|
||||
RazorViewResult viewResult = Assert.IsType<RazorViewResult>(result);
|
||||
FieldInfo? viewNameField = typeof(RazorViewResult).GetField("_viewName", BindingFlags.Instance | BindingFlags.NonPublic);
|
||||
Assert.NotNull(viewNameField);
|
||||
return (string)viewNameField.GetValue(viewResult)!;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the private model of the rendered <see cref="RazorViewResult"/>, which the result does not expose publicly.
|
||||
/// </summary>
|
||||
/// <param name="result">The result returned by the endpoint under test.</param>
|
||||
/// <returns>The model passed to the rendered view.</returns>
|
||||
private static object? GetRenderedModel(IResult result)
|
||||
{
|
||||
RazorViewResult viewResult = Assert.IsType<RazorViewResult>(result);
|
||||
FieldInfo? modelField = typeof(RazorViewResult).GetField("_model", BindingFlags.Instance | BindingFlags.NonPublic);
|
||||
Assert.NotNull(modelField);
|
||||
return modelField.GetValue(viewResult);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the page data carries the serialized deleted music items of the page.
|
||||
/// </summary>
|
||||
/// <param name="page">The page model passed to the theme renderer.</param>
|
||||
/// <param name="deletedArtists">The deleted artists expected in the page data.</param>
|
||||
/// <param name="deletedAlbums">The deleted albums expected in the page data.</param>
|
||||
/// <param name="deletedTracks">The deleted tracks expected in the page data.</param>
|
||||
/// <returns><see langword="true"/> when the serialized deleted items match the expected ones; otherwise <see langword="false"/>.</returns>
|
||||
private static bool HasDocumentedDeletedMusicItems(
|
||||
ThemePageDto page,
|
||||
DeletedMusicArtistDto[] deletedArtists,
|
||||
DeletedMusicAlbumDto[] deletedAlbums,
|
||||
DeletedMusicTrackDto[] deletedTracks)
|
||||
{
|
||||
if (!page.PageData.TryGetValue("deletedArtistsJson", out object? artistsValue) || artistsValue is not string artistsJson)
|
||||
return false;
|
||||
if (!page.PageData.TryGetValue("deletedAlbumsJson", out object? albumsValue) || albumsValue is not string albumsJson)
|
||||
return false;
|
||||
if (!page.PageData.TryGetValue("deletedTracksJson", out object? tracksValue) || tracksValue is not string tracksJson)
|
||||
return false;
|
||||
|
||||
using JsonDocument artistsDocument = JsonDocument.Parse(artistsJson);
|
||||
using JsonDocument albumsDocument = JsonDocument.Parse(albumsJson);
|
||||
using JsonDocument tracksDocument = JsonDocument.Parse(tracksJson);
|
||||
return artistsDocument.RootElement.GetArrayLength() == deletedArtists.Length
|
||||
&& string.Equals(artistsDocument.RootElement[0].GetProperty("name").GetString(), deletedArtists[0].Name, StringComparison.Ordinal)
|
||||
&& albumsDocument.RootElement.GetArrayLength() == deletedAlbums.Length
|
||||
&& string.Equals(albumsDocument.RootElement[0].GetProperty("title").GetString(), deletedAlbums[0].Title, StringComparison.Ordinal)
|
||||
&& tracksDocument.RootElement.GetArrayLength() == deletedTracks.Length
|
||||
&& string.Equals(tracksDocument.RootElement[0].GetProperty("albumTitle").GetString(), deletedTracks[0].AlbumTitle, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the page data carries the localized strings of the deleted music items page, both raw and serialized.
|
||||
/// </summary>
|
||||
/// <param name="page">The page model passed to the theme renderer.</param>
|
||||
/// <returns><see langword="true"/> when the localized strings are exposed and serialized; otherwise <see langword="false"/>.</returns>
|
||||
private static bool HasDocumentedLocalizedStrings(ThemePageDto page)
|
||||
{
|
||||
if (!page.PageData.TryGetValue("strings", out object? value) || value is not Dictionary<string, object?> strings)
|
||||
return false;
|
||||
if (!page.PageData.TryGetValue("stringsJson", out object? jsonValue) || jsonValue is not string stringsJson)
|
||||
return false;
|
||||
|
||||
using JsonDocument stringsDocument = JsonDocument.Parse(stringsJson);
|
||||
return string.Equals(strings["Title"] as string, "Deleted items", StringComparison.Ordinal)
|
||||
&& string.Equals(strings["NoDeletedItems"] as string, "There are no deleted items in this library.", StringComparison.Ordinal)
|
||||
&& string.Equals(stringsDocument.RootElement.GetProperty("title").GetString(), "Deleted items", StringComparison.Ordinal)
|
||||
&& string.Equals(stringsDocument.RootElement.GetProperty("noDeletedItems").GetString(), "There are no deleted items in this library.", StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the named property of an anonymous route values object is the empty Guid.
|
||||
/// </summary>
|
||||
/// <param name="routeValues">The anonymous route values object passed to the URL service.</param>
|
||||
/// <param name="propertyName">The name of the route value property to check.</param>
|
||||
private static void AssertRouteValueIsEmptyGuid(object? routeValues, string propertyName)
|
||||
{
|
||||
Assert.NotNull(routeValues);
|
||||
PropertyInfo? property = routeValues!.GetType().GetProperty(propertyName);
|
||||
Assert.NotNull(property);
|
||||
Assert.Equal(Guid.Empty, (Guid)property!.GetValue(routeValues)!);
|
||||
}
|
||||
}
|
||||
+152
@@ -0,0 +1,152 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.DeleteMusicTrack;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.DeleteMusicTrack;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="DeleteMusicTrackEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteMusicTrackEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly DeleteMusicTrackEndpoint _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteMusicTrackEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public DeleteMusicTrackEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<DeleteMusicTrackEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldDeleteTrackViaApiAndReturnSuccessWithoutData()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ConfigureRequest(artistId.ToString(), albumId.ToString(), trackId.ToString(), libraryId);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
BuildExpectedEndpoint(libraryId, artistId, albumId, trackId),
|
||||
Arg.Any<CancellationToken>());
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.False(jsonDocument.RootElement.TryGetProperty("data", out JsonElement _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteIdsAreNotParseable_ShouldForwardGuidEmptyIdsToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ConfigureRequest("not-a-guid", "not-a-guid", "not-a-guid", libraryId);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
BuildExpectedEndpoint(libraryId, Guid.Empty, Guid.Empty, Guid.Empty),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteIdsAreMissing_ShouldForwardGuidEmptyIdsToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={libraryId}");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
BuildExpectedEndpoint(libraryId, Guid.Empty, Guid.Empty, Guid.Empty),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenLibraryQueryIdIsNotParseable_ShouldForwardGuidEmptyLibraryIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
ConfigureRequest(artistId.ToString(), albumId.ToString(), trackId.ToString(), "not-a-guid");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
BuildExpectedEndpoint(Guid.Empty, artistId, albumId, trackId),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the route and query values the endpoint reads the track identities from.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The raw route value of the artist Id.</param>
|
||||
/// <param name="albumId">The raw route value of the album Id.</param>
|
||||
/// <param name="trackId">The raw route value of the track Id.</param>
|
||||
/// <param name="libraryId">The raw query value of the library Id.</param>
|
||||
private void ConfigureRequest(string artistId, string albumId, string trackId, Guid libraryId)
|
||||
{
|
||||
ConfigureRequest(artistId, albumId, trackId, libraryId.ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the route and query values the endpoint reads the track identities from.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The raw route value of the artist Id.</param>
|
||||
/// <param name="albumId">The raw route value of the album Id.</param>
|
||||
/// <param name="trackId">The raw route value of the track Id.</param>
|
||||
/// <param name="libraryId">The raw query value of the library Id.</param>
|
||||
private void ConfigureRequest(string artistId, string albumId, string trackId, string libraryId)
|
||||
{
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = artistId;
|
||||
_sut.HttpContext.Request.RouteValues["albumId"] = albumId;
|
||||
_sut.HttpContext.Request.RouteValues["trackId"] = trackId;
|
||||
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={libraryId}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the upstream endpoint the track deletion is expected to be sent to.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The normalized Id of the media library.</param>
|
||||
/// <param name="artistId">The normalized Id of the artist.</param>
|
||||
/// <param name="albumId">The normalized Id of the album.</param>
|
||||
/// <param name="trackId">The normalized Id of the track.</param>
|
||||
/// <returns>The expected upstream endpoint.</returns>
|
||||
private static string BuildExpectedEndpoint(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)
|
||||
{
|
||||
return ApiRoutes.Music.DELETE_TRACK
|
||||
.Replace("{libraryId}", libraryId.ToString())
|
||||
.Replace("{artistId}", artistId.ToString())
|
||||
.Replace("{albumId}", albumId.ToString())
|
||||
.Replace("{trackId}", trackId.ToString());
|
||||
}
|
||||
}
|
||||
+204
@@ -0,0 +1,204 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetAlbumTracks;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetAlbumTracks;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetAlbumTracksEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetAlbumTracksEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly GetAlbumTracksEndpoint _sut;
|
||||
private readonly GetAlbumTracksLiteRequestFixture _getAlbumTracksLiteRequestFixture = new();
|
||||
private readonly PaginatedDtoFixture<MusicTrackLiteDto> _paginatedMusicTrackLiteDtoFixture = new();
|
||||
private readonly MusicTrackLiteDtoFixture _musicTrackLiteDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetAlbumTracksEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetAlbumTracksEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<GetAlbumTracksEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalledWithPagination_ShouldRequestTracksWithQueryParameters()
|
||||
{
|
||||
// Arrange
|
||||
GetAlbumTracksLiteRequest request = _getAlbumTracksLiteRequestFixture.Create(currentPage: 2, perPage: 48);
|
||||
_mockApiHttpClient.GetAsync<PaginatedDto<MusicTrackLiteDto>>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedMusicTrackLiteDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedDto<MusicTrackLiteDto>>(
|
||||
Arg.Is<string>(endpoint => endpoint == $"{BuildExpectedEndpoint(request.LibraryId, Guid.Parse(request.ArtistId), Guid.Parse(request.AlbumId))}?currentPage=2&perPage=48"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalledWithoutPagination_ShouldRequestTracksWithoutQueryParameters()
|
||||
{
|
||||
// Arrange
|
||||
GetAlbumTracksLiteRequest request = _getAlbumTracksLiteRequestFixture.Create();
|
||||
_mockApiHttpClient.GetAsync<PaginatedDto<MusicTrackLiteDto>>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedMusicTrackLiteDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedDto<MusicTrackLiteDto>>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(request.LibraryId, Guid.Parse(request.ArtistId), Guid.Parse(request.AlbumId))),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOnlyCurrentPageIsProvided_ShouldAppendOnlyCurrentPage()
|
||||
{
|
||||
// Arrange
|
||||
GetAlbumTracksLiteRequest request = _getAlbumTracksLiteRequestFixture.Create(currentPage: 3);
|
||||
_mockApiHttpClient.GetAsync<PaginatedDto<MusicTrackLiteDto>>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedMusicTrackLiteDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedDto<MusicTrackLiteDto>>(
|
||||
Arg.Is<string>(endpoint => endpoint == $"{BuildExpectedEndpoint(request.LibraryId, Guid.Parse(request.ArtistId), Guid.Parse(request.AlbumId))}?currentPage=3"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOnlyPerPageIsProvided_ShouldAppendOnlyPerPage()
|
||||
{
|
||||
// Arrange
|
||||
GetAlbumTracksLiteRequest request = _getAlbumTracksLiteRequestFixture.Create(perPage: 24);
|
||||
_mockApiHttpClient.GetAsync<PaginatedDto<MusicTrackLiteDto>>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedMusicTrackLiteDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedDto<MusicTrackLiteDto>>(
|
||||
Arg.Is<string>(endpoint => endpoint == $"{BuildExpectedEndpoint(request.LibraryId, Guid.Parse(request.ArtistId), Guid.Parse(request.AlbumId))}?perPage=24"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenArtistIdIsNotParseable_ShouldForwardGuidEmptyArtistIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
GetAlbumTracksLiteRequest request = _getAlbumTracksLiteRequestFixture.Create(artistId: "not-a-guid", currentPage: 1, perPage: 20);
|
||||
_mockApiHttpClient.GetAsync<PaginatedDto<MusicTrackLiteDto>>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedMusicTrackLiteDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedDto<MusicTrackLiteDto>>(
|
||||
Arg.Is<string>(endpoint => endpoint == $"{BuildExpectedEndpoint(request.LibraryId, Guid.Empty, Guid.Parse(request.AlbumId))}?currentPage=1&perPage=20"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenAlbumIdIsNotParseable_ShouldForwardGuidEmptyAlbumIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
GetAlbumTracksLiteRequest request = _getAlbumTracksLiteRequestFixture.Create(albumId: "' OR '1'='1", currentPage: 1, perPage: 20);
|
||||
_mockApiHttpClient.GetAsync<PaginatedDto<MusicTrackLiteDto>>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedMusicTrackLiteDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedDto<MusicTrackLiteDto>>(
|
||||
Arg.Is<string>(endpoint => endpoint == $"{BuildExpectedEndpoint(request.LibraryId, Guid.Parse(request.ArtistId), Guid.Empty)}?currentPage=1&perPage=20"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenArtistIdAndAlbumIdAreMissing_ShouldForwardGuidEmptyIdsToApi()
|
||||
{
|
||||
// Arrange
|
||||
GetAlbumTracksLiteRequest request = _getAlbumTracksLiteRequestFixture.Create(artistId: string.Empty, albumId: string.Empty, currentPage: 1, perPage: 20);
|
||||
_mockApiHttpClient.GetAsync<PaginatedDto<MusicTrackLiteDto>>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedMusicTrackLiteDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedDto<MusicTrackLiteDto>>(
|
||||
Arg.Is<string>(endpoint => endpoint == $"{BuildExpectedEndpoint(request.LibraryId, Guid.Empty, Guid.Empty)}?currentPage=1&perPage=20"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsPaginatedTracks_ShouldReturnSuccessJsonWithTracks()
|
||||
{
|
||||
// Arrange
|
||||
GetAlbumTracksLiteRequest request = _getAlbumTracksLiteRequestFixture.Create();
|
||||
PaginatedDto<MusicTrackLiteDto> expectedResponse = _paginatedMusicTrackLiteDtoFixture.Create(
|
||||
data: [_musicTrackLiteDtoFixture.Create(title: "Test Track")],
|
||||
currentPage: 1,
|
||||
perPage: 20,
|
||||
count: 1,
|
||||
numberOfPages: 1);
|
||||
_mockApiHttpClient.GetAsync<PaginatedDto<MusicTrackLiteDto>>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedResponse);
|
||||
|
||||
// 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(1, data.GetProperty("currentPage").GetInt32());
|
||||
Assert.Equal(1, data.GetProperty("data").GetArrayLength());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the upstream endpoint the album track retrieval is expected to be sent to, without query parameters.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library.</param>
|
||||
/// <param name="artistId">The normalized Id of the artist.</param>
|
||||
/// <param name="albumId">The normalized Id of the album.</param>
|
||||
/// <returns>The expected upstream endpoint.</returns>
|
||||
private static string BuildExpectedEndpoint(Guid libraryId, Guid artistId, Guid albumId)
|
||||
{
|
||||
return ApiRoutes.Music.GET_ALBUM_TRACKS_LITE
|
||||
.Replace("{libraryId}", libraryId.ToString())
|
||||
.Replace("{artistId}", artistId.ToString())
|
||||
.Replace("{albumId}", albumId.ToString());
|
||||
}
|
||||
}
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetMusicTrack;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetMusicTrack;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetMusicTrackEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetMusicTrackEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly GetMusicTrackEndpoint _sut;
|
||||
private readonly GetMusicTrackViewRequestFixture _getMusicTrackViewRequestFixture = new();
|
||||
private readonly MusicTrackDtoFixture _musicTrackDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetMusicTrackEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetMusicTrackEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<GetMusicTrackEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldRequestTrackFromApiWithNormalizedIds()
|
||||
{
|
||||
// Arrange
|
||||
GetMusicTrackViewRequest request = _getMusicTrackViewRequestFixture.Create();
|
||||
MusicTrackDto expectedTrack = _musicTrackDtoFixture.Create();
|
||||
_mockApiHttpClient.GetAsync<MusicTrackDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedTrack);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<MusicTrackDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(request.LibraryId, Guid.Parse(request.ArtistId), Guid.Parse(request.AlbumId), Guid.Parse(request.TrackId))),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteIdsAreNotParseable_ShouldForwardGuidEmptyIdsToApi()
|
||||
{
|
||||
// Arrange
|
||||
GetMusicTrackViewRequest request = _getMusicTrackViewRequestFixture.Create(artistId: "not-a-guid", albumId: "' OR '1'='1", trackId: "'; DROP TABLE Tracks; --");
|
||||
_mockApiHttpClient.GetAsync<MusicTrackDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_musicTrackDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<MusicTrackDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(request.LibraryId, Guid.Empty, Guid.Empty, Guid.Empty)),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteIdsAreEmpty_ShouldForwardGuidEmptyIdsToApi()
|
||||
{
|
||||
// Arrange
|
||||
GetMusicTrackViewRequest request = _getMusicTrackViewRequestFixture.Create(artistId: string.Empty, albumId: string.Empty, trackId: string.Empty);
|
||||
_mockApiHttpClient.GetAsync<MusicTrackDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_musicTrackDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<MusicTrackDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(request.LibraryId, Guid.Empty, Guid.Empty, Guid.Empty)),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsTrack_ShouldReturnSuccessJsonWithTrack()
|
||||
{
|
||||
// Arrange
|
||||
GetMusicTrackViewRequest request = _getMusicTrackViewRequestFixture.Create();
|
||||
MusicTrackDto expectedTrack = _musicTrackDtoFixture.Create();
|
||||
_mockApiHttpClient.GetAsync<MusicTrackDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedTrack);
|
||||
|
||||
// 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());
|
||||
Assert.Equal(expectedTrack.Id, jsonDocument.RootElement.GetProperty("data").GetProperty("id").GetGuid());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the upstream endpoint the track retrieval is expected to be sent to.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The normalized Id of the media library.</param>
|
||||
/// <param name="artistId">The normalized Id of the artist.</param>
|
||||
/// <param name="albumId">The normalized Id of the album.</param>
|
||||
/// <param name="trackId">The normalized Id of the track.</param>
|
||||
/// <returns>The expected upstream endpoint.</returns>
|
||||
private static string BuildExpectedEndpoint(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)
|
||||
{
|
||||
return ApiRoutes.Music.GET_TRACK
|
||||
.Replace("{libraryId}", libraryId.ToString())
|
||||
.Replace("{artistId}", artistId.ToString())
|
||||
.Replace("{albumId}", albumId.ToString())
|
||||
.Replace("{trackId}", trackId.ToString());
|
||||
}
|
||||
}
|
||||
+261
@@ -0,0 +1,261 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetPlaybackManifest;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetPlaybackManifest;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetPlaybackManifestEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetPlaybackManifestEndpointTests
|
||||
{
|
||||
private const string VALID_DELIVERY_ID = "0123456789abcdef0123456789abcdef";
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly GetPlaybackManifestEndpoint _sut;
|
||||
private readonly GetPlaybackManifestRequestFixture _getPlaybackManifestRequestFixture = new();
|
||||
private readonly PlaybackManifestDtoFixture _playbackManifestDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPlaybackManifestEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetPlaybackManifestEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<GetPlaybackManifestEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenManifestIsNotADirectPlay_ShouldRewriteTheStreamPathsToTheWebProxyRoutes()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
string artistId = Guid.NewGuid().ToString();
|
||||
string albumId = Guid.NewGuid().ToString();
|
||||
string trackId = Guid.NewGuid().ToString();
|
||||
GetPlaybackManifestRequest request = _getPlaybackManifestRequestFixture.Create(
|
||||
artistId: artistId,
|
||||
albumId: albumId,
|
||||
trackId: trackId,
|
||||
libraryId: libraryId,
|
||||
includeCapabilities: false);
|
||||
PlaybackManifestDto manifest = _playbackManifestDtoFixture.Create(
|
||||
isDirectPlay: false,
|
||||
deliveryId: VALID_DELIVERY_ID,
|
||||
streamPath: "/api/v1/libraries/ancient/stream",
|
||||
segmentStreamPathTemplate: "/api/v1/libraries/ancient/stream/deliveries/{deliveryId}/segments/{segmentIndex}");
|
||||
_mockApiHttpClient.GetAsync<PlaybackManifestDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(manifest);
|
||||
string expectedStreamPath = $"/en-US/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-stream-track?libraryId={libraryId}";
|
||||
string expectedSegmentStreamPathTemplate = $"/en-US/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-stream-track-segment/{{deliveryId}}/{{segmentIndex}}?libraryId={libraryId}";
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
using JsonDocument json = JsonDocument.Parse(await JsonResultTestHelper.GetResponseBodyAsync(result));
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
JsonElement data = json.RootElement.GetProperty("data");
|
||||
Assert.Equal(expectedStreamPath, data.GetProperty("streamPath").GetString());
|
||||
Assert.Equal(expectedSegmentStreamPathTemplate, data.GetProperty("segmentStreamPathTemplate").GetString());
|
||||
Assert.Equal(VALID_DELIVERY_ID, data.GetProperty("deliveryId").GetString());
|
||||
Assert.DoesNotContain("http", data.GetProperty("streamPath").GetString(), StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("http", data.GetProperty("segmentStreamPathTemplate").GetString(), StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString());
|
||||
Assert.Equal("Cookie", _sut.HttpContext.Response.Headers["Vary"].ToString());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(true)] // A null template means the delivery has no segment route.
|
||||
[InlineData(false)] // An empty template means the delivery has no segment route.
|
||||
public async Task ExecuteAsync_WhenSegmentPathTemplateIsEmpty_ShouldClearTheDeliveryIdAndTheTemplate(bool useNullTemplate)
|
||||
{
|
||||
// Arrange
|
||||
GetPlaybackManifestRequest request = _getPlaybackManifestRequestFixture.Create(includeCapabilities: false);
|
||||
PlaybackManifestDto manifest = _playbackManifestDtoFixture.Create(
|
||||
isDirectPlay: false,
|
||||
deliveryId: VALID_DELIVERY_ID,
|
||||
segmentStreamPathTemplate: useNullTemplate ? null : string.Empty,
|
||||
includeSegmentStreamPathTemplate: !useNullTemplate);
|
||||
_mockApiHttpClient.GetAsync<PlaybackManifestDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(manifest);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
using JsonDocument json = JsonDocument.Parse(await JsonResultTestHelper.GetResponseBodyAsync(result));
|
||||
JsonElement data = json.RootElement.GetProperty("data");
|
||||
Assert.Equal(JsonValueKind.Null, data.GetProperty("deliveryId").ValueKind);
|
||||
Assert.Equal(JsonValueKind.Null, data.GetProperty("segmentStreamPathTemplate").ValueKind);
|
||||
Assert.NotEqual(JsonValueKind.Null, data.GetProperty("streamPath").ValueKind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSegmentPathTemplateIsPresentButDeliveryIdIsInvalid_ShouldThrowBadGatewayApiException()
|
||||
{
|
||||
// Arrange
|
||||
GetPlaybackManifestRequest request = _getPlaybackManifestRequestFixture.Create(includeCapabilities: false);
|
||||
PlaybackManifestDto manifest = _playbackManifestDtoFixture.Create(
|
||||
isDirectPlay: false,
|
||||
deliveryId: "not-a-valid-handle",
|
||||
segmentStreamPathTemplate: "/api/v1/libraries/ancient/stream/deliveries/{deliveryId}/segments/{segmentIndex}");
|
||||
_mockApiHttpClient.GetAsync<PlaybackManifestDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(manifest);
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
ApiException apiException = await Assert.ThrowsAsync<ApiException>(() => operationTask);
|
||||
Assert.Equal(HttpStatusCode.BadGateway, apiException.HttpStatusCode);
|
||||
Assert.NotNull(apiException.ProblemDetails);
|
||||
Assert.Equal("General.Failure", apiException.ProblemDetails!.Title);
|
||||
Assert.Equal("InternalServerError", apiException.ProblemDetails.Detail);
|
||||
Assert.Equal(StatusCodes.Status502BadGateway, apiException.ProblemDetails.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsNoManifest_ShouldThrowBadGatewayApiException()
|
||||
{
|
||||
// Arrange
|
||||
GetPlaybackManifestRequest request = _getPlaybackManifestRequestFixture.Create(includeCapabilities: false);
|
||||
_mockApiHttpClient.GetAsync<PlaybackManifestDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromResult<PlaybackManifestDto>(null!));
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
ApiException apiException = await Assert.ThrowsAsync<ApiException>(() => operationTask);
|
||||
Assert.Equal(HttpStatusCode.BadGateway, apiException.HttpStatusCode);
|
||||
Assert.NotNull(apiException.ProblemDetails);
|
||||
Assert.Equal("General.Failure", apiException.ProblemDetails!.Title);
|
||||
Assert.Equal("InternalServerError", apiException.ProblemDetails.Detail);
|
||||
Assert.Equal(StatusCodes.Status502BadGateway, apiException.ProblemDetails.Status);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("mp3/mp3", "?capabilities=mp3%2Fmp3")] // The capabilities are forwarded and URL-escaped.
|
||||
[InlineData("flac/flac,mp3/mp3", "?capabilities=flac%2Fflac%2Cmp3%2Fmp3")] // A capability list is forwarded as one escaped value.
|
||||
[InlineData(" ", "")] // Whitespace only capabilities are not forwarded.
|
||||
[InlineData(null, "")] // Absent capabilities are not forwarded.
|
||||
public async Task ExecuteAsync_WhenCapabilitiesAreProvided_ShouldForwardThemOnlyWhenTheyAreNotEmpty(string? capabilities, string expectedSuffix)
|
||||
{
|
||||
// Arrange
|
||||
string artistId = Guid.NewGuid().ToString();
|
||||
string albumId = Guid.NewGuid().ToString();
|
||||
string trackId = Guid.NewGuid().ToString();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
GetPlaybackManifestRequest request = _getPlaybackManifestRequestFixture.Create(
|
||||
artistId: artistId,
|
||||
albumId: albumId,
|
||||
trackId: trackId,
|
||||
libraryId: libraryId,
|
||||
capabilities: capabilities,
|
||||
includeCapabilities: capabilities is not null);
|
||||
string expectedEndpoint = ApiRoutes.Music.GET_PLAYBACK_MANIFEST
|
||||
.Replace("{libraryId}", libraryId.ToString())
|
||||
.Replace("{artistId}", artistId)
|
||||
.Replace("{albumId}", albumId)
|
||||
.Replace("{trackId}", trackId) + expectedSuffix;
|
||||
_mockApiHttpClient.GetAsync<PlaybackManifestDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_playbackManifestDtoFixture.Create(deliveryId: VALID_DELIVERY_ID));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PlaybackManifestDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == expectedEndpoint),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteIdsAreNotParseable_ShouldForwardEmptyGuidsToTheApi()
|
||||
{
|
||||
// Arrange
|
||||
GetPlaybackManifestRequest request = _getPlaybackManifestRequestFixture.Create(artistId: "not-a-guid", albumId: "' OR '1'='1", trackId: "'; DROP TABLE Tracks; --", includeCapabilities: false);
|
||||
string expectedEndpoint = ApiRoutes.Music.GET_PLAYBACK_MANIFEST
|
||||
.Replace("{libraryId}", request.LibraryId.ToString())
|
||||
.Replace("{artistId}", Guid.Empty.ToString())
|
||||
.Replace("{albumId}", Guid.Empty.ToString())
|
||||
.Replace("{trackId}", Guid.Empty.ToString());
|
||||
_mockApiHttpClient.GetAsync<PlaybackManifestDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_playbackManifestDtoFixture.Create(deliveryId: VALID_DELIVERY_ID));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PlaybackManifestDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == expectedEndpoint),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("/lumina", "/lumina")] // A plain absolute path base is prefixed.
|
||||
[InlineData("//evil", "")] // A protocol relative path base would point the stream at another origin.
|
||||
[InlineData("/a?b", "")] // A path base with a query would truncate the built path.
|
||||
public async Task ExecuteAsync_WhenPathBaseIsPresent_ShouldUseItOnlyWhenItIsSafe(string pathBase, string expectedPrefix)
|
||||
{
|
||||
// Arrange
|
||||
GetPlaybackManifestRequest request = _getPlaybackManifestRequestFixture.Create(includeCapabilities: false);
|
||||
_sut.HttpContext.Request.PathBase = pathBase;
|
||||
_mockApiHttpClient.GetAsync<PlaybackManifestDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_playbackManifestDtoFixture.Create(deliveryId: VALID_DELIVERY_ID));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
using JsonDocument json = JsonDocument.Parse(await JsonResultTestHelper.GetResponseBodyAsync(result));
|
||||
string? streamPath = json.RootElement.GetProperty("data").GetProperty("streamPath").GetString();
|
||||
Assert.NotNull(streamPath);
|
||||
Assert.StartsWith($"{expectedPrefix}/en-US/library/audio-library/music-library/artists/", streamPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
GetPlaybackManifestRequest request = _getPlaybackManifestRequestFixture.Create(includeCapabilities: false);
|
||||
CancellationTokenSource cancellationTokenSource = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
_mockApiHttpClient.GetAsync<PlaybackManifestDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return _playbackManifestDtoFixture.Create(deliveryId: VALID_DELIVERY_ID);
|
||||
}, callInfo.Arg<CancellationToken>()));
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(request, cancellationTokenSource.Token);
|
||||
await operationStarted.Task;
|
||||
cancellationTokenSource.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
}
|
||||
+262
@@ -0,0 +1,262 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.RestoreMusicTrack;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.RestoreMusicTrack;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="RestoreMusicTrackEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RestoreMusicTrackEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly RestoreMusicTrackEndpoint _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RestoreMusicTrackEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public RestoreMusicTrackEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<RestoreMusicTrackEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("D")] // Standard hyphenated format.
|
||||
[InlineData("B")] // Braced format.
|
||||
[InlineData("N")] // Compact format.
|
||||
[InlineData("P")] // Parenthesized format.
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldRestoreTrackViaApiWithNormalizedIdsAndReturnSuccessPayload(string guidFormat)
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ConfigureRequest(artistId.ToString(guidFormat), albumId.ToString(guidFormat), trackId.ToString(guidFormat), libraryId.ToString(guidFormat));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync(
|
||||
BuildExpectedEndpoint(libraryId, artistId, albumId, trackId),
|
||||
Arg.Any<CancellationToken>());
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("data").GetProperty("isRestored").GetBoolean());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenArtistRouteIdIsNotParseable_ShouldForwardGuidEmptyArtistIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ConfigureRequest("not-a-guid", albumId.ToString(), trackId.ToString(), libraryId.ToString());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync(
|
||||
BuildExpectedEndpoint(libraryId, Guid.Empty, albumId, trackId),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenArtistRouteIdIsMissing_ShouldForwardGuidEmptyArtistIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ConfigureRequest(null, albumId.ToString(), trackId.ToString(), libraryId.ToString());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync(
|
||||
BuildExpectedEndpoint(libraryId, Guid.Empty, albumId, trackId),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenAlbumRouteIdIsNotParseable_ShouldForwardGuidEmptyAlbumIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ConfigureRequest(artistId.ToString(), "not-a-guid", trackId.ToString(), libraryId.ToString());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync(
|
||||
BuildExpectedEndpoint(libraryId, artistId, Guid.Empty, trackId),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenAlbumRouteIdIsMissing_ShouldForwardGuidEmptyAlbumIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ConfigureRequest(artistId.ToString(), null, trackId.ToString(), libraryId.ToString());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync(
|
||||
BuildExpectedEndpoint(libraryId, artistId, Guid.Empty, trackId),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenTrackRouteIdIsNotParseable_ShouldForwardGuidEmptyTrackIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ConfigureRequest(artistId.ToString(), albumId.ToString(), "not-a-guid", libraryId.ToString());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync(
|
||||
BuildExpectedEndpoint(libraryId, artistId, albumId, Guid.Empty),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenTrackRouteIdIsMissing_ShouldForwardGuidEmptyTrackIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ConfigureRequest(artistId.ToString(), albumId.ToString(), null, libraryId.ToString());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync(
|
||||
BuildExpectedEndpoint(libraryId, artistId, albumId, Guid.Empty),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenLibraryQueryIdIsNotParseable_ShouldForwardGuidEmptyLibraryIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
ConfigureRequest(artistId.ToString(), albumId.ToString(), trackId.ToString(), "not-a-guid");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync(
|
||||
BuildExpectedEndpoint(Guid.Empty, artistId, albumId, trackId),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenLibraryQueryIdIsMissing_ShouldForwardGuidEmptyLibraryIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
ConfigureRequest(artistId.ToString(), albumId.ToString(), trackId.ToString(), null);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync(
|
||||
BuildExpectedEndpoint(Guid.Empty, artistId, albumId, trackId),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ConfigureRequest(artistId.ToString(), albumId.ToString(), trackId.ToString(), libraryId.ToString());
|
||||
using CancellationTokenSource cancellationTokenSource = new();
|
||||
cancellationTokenSource.Cancel();
|
||||
_mockApiHttpClient.PostIgnoringResponseAsync(
|
||||
Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromCanceled(cancellationTokenSource.Token));
|
||||
|
||||
// Act & Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(
|
||||
() => _sut.ExecuteAsync(EmptyRequest.Instance, cancellationTokenSource.Token));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the route and query values the endpoint reads the track identity from.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The raw route value of the artist Id, or <see langword="null"/> to leave the route value missing.</param>
|
||||
/// <param name="albumId">The raw route value of the album Id, or <see langword="null"/> to leave the route value missing.</param>
|
||||
/// <param name="trackId">The raw route value of the track Id, or <see langword="null"/> to leave the route value missing.</param>
|
||||
/// <param name="libraryId">The raw query value of the library Id, or <see langword="null"/> to leave the query string missing.</param>
|
||||
private void ConfigureRequest(string? artistId, string? albumId, string? trackId, string? libraryId)
|
||||
{
|
||||
if (artistId is not null)
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = artistId;
|
||||
if (albumId is not null)
|
||||
_sut.HttpContext.Request.RouteValues["albumId"] = albumId;
|
||||
if (trackId is not null)
|
||||
_sut.HttpContext.Request.RouteValues["trackId"] = trackId;
|
||||
if (libraryId is not null)
|
||||
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={libraryId}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the upstream endpoint the track restoration is expected to be sent to.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The normalized Id of the media library.</param>
|
||||
/// <param name="artistId">The normalized Id of the artist.</param>
|
||||
/// <param name="albumId">The normalized Id of the album.</param>
|
||||
/// <param name="trackId">The normalized Id of the track.</param>
|
||||
/// <returns>The expected upstream endpoint.</returns>
|
||||
private static string BuildExpectedEndpoint(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)
|
||||
{
|
||||
return ApiRoutes.Music.RESTORE_TRACK
|
||||
.Replace("{libraryId}", libraryId.ToString())
|
||||
.Replace("{artistId}", artistId.ToString())
|
||||
.Replace("{albumId}", albumId.ToString())
|
||||
.Replace("{trackId}", trackId.ToString());
|
||||
}
|
||||
}
|
||||
+245
@@ -0,0 +1,245 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.SaveMusicTrack;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.SaveMusicTrack;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="SaveMusicTrackEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SaveMusicTrackEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly SaveMusicTrackEndpoint _sut;
|
||||
private readonly UpdateMusicTrackRequestFixture _updateMusicTrackRequestFixture = new();
|
||||
private readonly MusicTrackDtoFixture _musicTrackDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SaveMusicTrackEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public SaveMusicTrackEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<SaveMusicTrackEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldForwardUpdateMusicTrackRequestToApiWithRouteAndQueryIds()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
UpdateMusicTrackRequest request = _updateMusicTrackRequestFixture.Create();
|
||||
MusicTrackDto expectedTrack = _musicTrackDtoFixture.Create();
|
||||
_mockApiHttpClient.PutAsync<MusicTrackDto, UpdateMusicTrackRequest>(Arg.Any<string>(), Arg.Any<UpdateMusicTrackRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedTrack);
|
||||
ConfigureRequest(artistId.ToString(), albumId.ToString(), trackId.ToString(), libraryId);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutAsync<MusicTrackDto, UpdateMusicTrackRequest>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(libraryId, artistId, albumId, trackId)),
|
||||
Arg.Is<UpdateMusicTrackRequest>(forwardedRequest => forwardedRequest == request),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenArtistRouteIdIsNotParseable_ShouldForwardGuidEmptyArtistIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
const string MALICIOUS_ARTIST_ID = "not-a-guid";
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
UpdateMusicTrackRequest request = _updateMusicTrackRequestFixture.Create();
|
||||
_mockApiHttpClient.PutAsync<MusicTrackDto, UpdateMusicTrackRequest>(Arg.Any<string>(), Arg.Any<UpdateMusicTrackRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_musicTrackDtoFixture.Create());
|
||||
ConfigureRequest(MALICIOUS_ARTIST_ID, albumId.ToString(), trackId.ToString(), libraryId);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutAsync<MusicTrackDto, UpdateMusicTrackRequest>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(libraryId, Guid.Empty, albumId, trackId)),
|
||||
Arg.Any<UpdateMusicTrackRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenAlbumRouteIdIsNotParseable_ShouldForwardGuidEmptyAlbumIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
const string MALICIOUS_ALBUM_ID = "' OR '1'='1";
|
||||
Guid trackId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
UpdateMusicTrackRequest request = _updateMusicTrackRequestFixture.Create();
|
||||
_mockApiHttpClient.PutAsync<MusicTrackDto, UpdateMusicTrackRequest>(Arg.Any<string>(), Arg.Any<UpdateMusicTrackRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_musicTrackDtoFixture.Create());
|
||||
ConfigureRequest(artistId.ToString(), MALICIOUS_ALBUM_ID, trackId.ToString(), libraryId);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutAsync<MusicTrackDto, UpdateMusicTrackRequest>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(libraryId, artistId, Guid.Empty, trackId)),
|
||||
Arg.Any<UpdateMusicTrackRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenTrackRouteIdIsNotParseable_ShouldForwardGuidEmptyTrackIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
const string MALICIOUS_TRACK_ID = "'; DROP TABLE Tracks; --";
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
UpdateMusicTrackRequest request = _updateMusicTrackRequestFixture.Create();
|
||||
_mockApiHttpClient.PutAsync<MusicTrackDto, UpdateMusicTrackRequest>(Arg.Any<string>(), Arg.Any<UpdateMusicTrackRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_musicTrackDtoFixture.Create());
|
||||
ConfigureRequest(artistId.ToString(), albumId.ToString(), MALICIOUS_TRACK_ID, libraryId);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutAsync<MusicTrackDto, UpdateMusicTrackRequest>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(libraryId, artistId, albumId, Guid.Empty)),
|
||||
Arg.Any<UpdateMusicTrackRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteIdsAreMissing_ShouldForwardGuidEmptyIdsToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
UpdateMusicTrackRequest request = _updateMusicTrackRequestFixture.Create();
|
||||
_mockApiHttpClient.PutAsync<MusicTrackDto, UpdateMusicTrackRequest>(Arg.Any<string>(), Arg.Any<UpdateMusicTrackRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_musicTrackDtoFixture.Create());
|
||||
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={libraryId}");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutAsync<MusicTrackDto, UpdateMusicTrackRequest>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(libraryId, Guid.Empty, Guid.Empty, Guid.Empty)),
|
||||
Arg.Any<UpdateMusicTrackRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenLibraryQueryIdIsNotParseable_ShouldForwardGuidEmptyLibraryIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
const string MALICIOUS_LIBRARY_ID = "not-a-guid";
|
||||
UpdateMusicTrackRequest request = _updateMusicTrackRequestFixture.Create();
|
||||
_mockApiHttpClient.PutAsync<MusicTrackDto, UpdateMusicTrackRequest>(Arg.Any<string>(), Arg.Any<UpdateMusicTrackRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_musicTrackDtoFixture.Create());
|
||||
ConfigureRequest(artistId.ToString(), albumId.ToString(), trackId.ToString(), MALICIOUS_LIBRARY_ID);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutAsync<MusicTrackDto, UpdateMusicTrackRequest>(
|
||||
Arg.Is<string>(endpoint => endpoint == BuildExpectedEndpoint(Guid.Empty, artistId, albumId, trackId)),
|
||||
Arg.Any<UpdateMusicTrackRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsUpdatedTrack_ShouldReturnSuccessJsonWithTrack()
|
||||
{
|
||||
// Arrange
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
UpdateMusicTrackRequest request = _updateMusicTrackRequestFixture.Create();
|
||||
MusicTrackDto expectedTrack = _musicTrackDtoFixture.Create();
|
||||
_mockApiHttpClient.PutAsync<MusicTrackDto, UpdateMusicTrackRequest>(Arg.Any<string>(), Arg.Any<UpdateMusicTrackRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedTrack);
|
||||
ConfigureRequest(artistId.ToString(), albumId.ToString(), trackId.ToString(), libraryId);
|
||||
|
||||
// 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());
|
||||
Assert.Equal(expectedTrack.Id, jsonDocument.RootElement.GetProperty("data").GetProperty("id").GetGuid());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the route and query values the endpoint reads the track identities from.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The raw route value of the artist Id.</param>
|
||||
/// <param name="albumId">The raw route value of the album Id.</param>
|
||||
/// <param name="trackId">The raw route value of the track Id.</param>
|
||||
/// <param name="libraryId">The raw query value of the library Id.</param>
|
||||
private void ConfigureRequest(string artistId, string albumId, string trackId, Guid libraryId)
|
||||
{
|
||||
ConfigureRequest(artistId, albumId, trackId, libraryId.ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the route and query values the endpoint reads the track identities from.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The raw route value of the artist Id.</param>
|
||||
/// <param name="albumId">The raw route value of the album Id.</param>
|
||||
/// <param name="trackId">The raw route value of the track Id.</param>
|
||||
/// <param name="libraryId">The raw query value of the library Id.</param>
|
||||
private void ConfigureRequest(string artistId, string albumId, string trackId, string libraryId)
|
||||
{
|
||||
_sut.HttpContext.Request.RouteValues["artistId"] = artistId;
|
||||
_sut.HttpContext.Request.RouteValues["albumId"] = albumId;
|
||||
_sut.HttpContext.Request.RouteValues["trackId"] = trackId;
|
||||
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={libraryId}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the upstream endpoint the track update is expected to be sent to.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The normalized Id of the media library.</param>
|
||||
/// <param name="artistId">The normalized Id of the artist.</param>
|
||||
/// <param name="albumId">The normalized Id of the album.</param>
|
||||
/// <param name="trackId">The normalized Id of the track.</param>
|
||||
/// <returns>The expected upstream endpoint.</returns>
|
||||
private static string BuildExpectedEndpoint(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)
|
||||
{
|
||||
return ApiRoutes.Music.UPDATE_TRACK
|
||||
.Replace("{libraryId}", libraryId.ToString())
|
||||
.Replace("{artistId}", artistId.ToString())
|
||||
.Replace("{albumId}", albumId.ToString())
|
||||
.Replace("{trackId}", trackId.ToString());
|
||||
}
|
||||
}
|
||||
+164
@@ -0,0 +1,164 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.ShuffleTracks;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.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.Library.AudioLibrary.MusicLibrary.Tracks.ShuffleTracks;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ShuffleTracksEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ShuffleTracksEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly ShuffleTracksEndpoint _sut;
|
||||
private readonly ShuffleTracksRequestFixture _shuffleTracksRequestFixture = new();
|
||||
private readonly MusicShuffleTrackDtoFixture _musicShuffleTrackDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ShuffleTracksEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public ShuffleTracksEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<ShuffleTracksEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsTracks_ShouldReturnSuccessJsonWithTheMappedTracks()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
ShuffleTracksRequest request = _shuffleTracksRequestFixture.Create(libraryId: libraryId);
|
||||
MusicShuffleTrackDto expectedTrack = _musicShuffleTrackDtoFixture.Create(
|
||||
trackId: trackId,
|
||||
title: "Bohemian Rhapsody",
|
||||
durationInSeconds: 355,
|
||||
albumId: albumId,
|
||||
albumTitle: "A Night at the Opera",
|
||||
artistId: artistId,
|
||||
coverPath: "a-night-at-the-opera-cover.jpg");
|
||||
_mockApiHttpClient.PostAsync<List<MusicShuffleTrackDto>, ShuffleTracksRequest>(Arg.Any<string>(), Arg.Any<ShuffleTracksRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns([expectedTrack]);
|
||||
|
||||
// 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(1, data.GetArrayLength());
|
||||
JsonElement track = data[0];
|
||||
Assert.Equal(trackId, track.GetProperty("trackId").GetGuid());
|
||||
Assert.Equal("Bohemian Rhapsody", track.GetProperty("title").GetString());
|
||||
Assert.Equal(355, track.GetProperty("durationInSeconds").GetInt32());
|
||||
Assert.Equal(albumId, track.GetProperty("albumId").GetGuid());
|
||||
Assert.Equal("A Night at the Opera", track.GetProperty("albumTitle").GetString());
|
||||
Assert.Equal(artistId, track.GetProperty("artistId").GetGuid());
|
||||
Assert.Equal("a-night-at-the-opera-cover.jpg", track.GetProperty("coverPath").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsNoTracks_ShouldReturnAnEmptyDataArray()
|
||||
{
|
||||
// Arrange
|
||||
ShuffleTracksRequest request = _shuffleTracksRequestFixture.Create();
|
||||
_mockApiHttpClient.PostAsync<List<MusicShuffleTrackDto>, ShuffleTracksRequest>(Arg.Any<string>(), Arg.Any<ShuffleTracksRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns([]);
|
||||
|
||||
// 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(JsonValueKind.Array, data.ValueKind);
|
||||
Assert.Equal(0, data.GetArrayLength());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldPostTheRequestToTheLibraryShuffleEndpoint()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid firstExcludedTrackId = Guid.NewGuid();
|
||||
Guid secondExcludedTrackId = Guid.NewGuid();
|
||||
ShuffleTracksRequest request = _shuffleTracksRequestFixture.Create(
|
||||
libraryId: libraryId,
|
||||
count: 25,
|
||||
artistId: artistId,
|
||||
albumId: albumId,
|
||||
excludedTrackIds: [firstExcludedTrackId, secondExcludedTrackId]);
|
||||
string expectedEndpoint = ApiRoutes.Music.SHUFFLE_TRACKS.Replace("{libraryId}", libraryId.ToString());
|
||||
_mockApiHttpClient.PostAsync<List<MusicShuffleTrackDto>, ShuffleTracksRequest>(Arg.Any<string>(), Arg.Any<ShuffleTracksRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns([]);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostAsync<List<MusicShuffleTrackDto>, ShuffleTracksRequest>(
|
||||
Arg.Is<string>(endpoint => endpoint == expectedEndpoint),
|
||||
Arg.Is<ShuffleTracksRequest>(forwarded =>
|
||||
forwarded.LibraryId == libraryId &&
|
||||
forwarded.Count == 25 &&
|
||||
forwarded.ArtistId == artistId &&
|
||||
forwarded.AlbumId == albumId &&
|
||||
forwarded.ExcludedTrackIds != null &&
|
||||
forwarded.ExcludedTrackIds.SequenceEqual(new[] { firstExcludedTrackId, secondExcludedTrackId })),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
ShuffleTracksRequest request = _shuffleTracksRequestFixture.Create();
|
||||
CancellationTokenSource cancellationTokenSource = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
_mockApiHttpClient.PostAsync<List<MusicShuffleTrackDto>, ShuffleTracksRequest>(Arg.Any<string>(), Arg.Any<ShuffleTracksRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return new List<MusicShuffleTrackDto> { _musicShuffleTrackDtoFixture.Create() };
|
||||
}, callInfo.Arg<CancellationToken>()));
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(request, cancellationTokenSource.Token);
|
||||
await operationStarted.Task;
|
||||
cancellationTokenSource.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
}
|
||||
+268
@@ -0,0 +1,268 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.StreamMusicTrack;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.StreamMusicTrack;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="StreamMusicTrackEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class StreamMusicTrackEndpointTests
|
||||
{
|
||||
private readonly IStreamingApiHttpClient _mockStreamingApiHttpClient;
|
||||
private readonly StreamMusicTrackEndpoint _sut;
|
||||
private readonly StreamMusicTrackRequestFixture _streamMusicTrackRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="StreamMusicTrackEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public StreamMusicTrackEndpointTests()
|
||||
{
|
||||
_mockStreamingApiHttpClient = Substitute.For<IStreamingApiHttpClient>();
|
||||
_sut = Factory.Create<StreamMusicTrackEndpoint>(_mockStreamingApiHttpClient);
|
||||
_sut.HttpContext.Response.Body = new MemoryStream();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldStreamTheTrackAndReturnEmptyResult()
|
||||
{
|
||||
// Arrange
|
||||
StreamMusicTrackRequest request = _streamMusicTrackRequestFixture.Create();
|
||||
string expectedEndpoint = BuildExpectedEndpoint(request);
|
||||
byte[] contentBytes = CreateBytes(1024);
|
||||
ApiStreamResult streamResult = await CreateStreamResultAsync(HttpStatusCode.OK, contentBytes, "audio/flac");
|
||||
_mockStreamingApiHttpClient.GetStreamAsync(Arg.Any<string>(), Arg.Any<IReadOnlyDictionary<string, string>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(streamResult);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.IsType<EmptyHttpResult>(result);
|
||||
await _mockStreamingApiHttpClient.Received(1).GetStreamAsync(
|
||||
Arg.Is<string>(endpoint => endpoint == expectedEndpoint),
|
||||
Arg.Any<IReadOnlyDictionary<string, string>>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
Assert.Equal(StatusCodes.Status200OK, _sut.HttpContext.Response.StatusCode);
|
||||
Assert.Equal("audio/flac", _sut.HttpContext.Response.ContentType);
|
||||
Assert.Equal(contentBytes.Length, _sut.HttpContext.Response.ContentLength);
|
||||
Assert.Equal(contentBytes, ReadResponseBody(_sut.HttpContext));
|
||||
Assert.Equal("Cookie", _sut.HttpContext.Response.Headers["Vary"].ToString());
|
||||
Assert.Contains("private", _sut.HttpContext.Response.Headers["Cache-Control"].ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenConditionalHeadersArePresent_ShouldForwardThemExactly()
|
||||
{
|
||||
// Arrange
|
||||
StreamMusicTrackRequest request = _streamMusicTrackRequestFixture.Create();
|
||||
_sut.HttpContext.Request.Headers["Range"] = "bytes=100-199";
|
||||
_sut.HttpContext.Request.Headers["If-Range"] = "\"etag-value\"";
|
||||
_sut.HttpContext.Request.Headers["If-None-Match"] = "\"etag-value\"";
|
||||
_sut.HttpContext.Request.Headers["If-Modified-Since"] = "Wed, 21 Oct 2015 07:28:00 GMT";
|
||||
_mockStreamingApiHttpClient.GetStreamAsync(Arg.Any<string>(), Arg.Any<IReadOnlyDictionary<string, string>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(await CreateStreamResultAsync(HttpStatusCode.OK, CreateBytes(16)));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockStreamingApiHttpClient.Received(1).GetStreamAsync(
|
||||
Arg.Any<string>(),
|
||||
Arg.Is<IReadOnlyDictionary<string, string>>(headers =>
|
||||
headers.Count == 4 &&
|
||||
headers["Range"] == "bytes=100-199" &&
|
||||
headers["If-Range"] == "\"etag-value\"" &&
|
||||
headers["If-None-Match"] == "\"etag-value\"" &&
|
||||
headers["If-Modified-Since"] == "Wed, 21 Oct 2015 07:28:00 GMT"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenConditionalHeadersAreAbsentOrWhitespace_ShouldNotForwardThem()
|
||||
{
|
||||
// Arrange
|
||||
StreamMusicTrackRequest request = _streamMusicTrackRequestFixture.Create();
|
||||
_sut.HttpContext.Request.Headers["Range"] = " ";
|
||||
_mockStreamingApiHttpClient.GetStreamAsync(Arg.Any<string>(), Arg.Any<IReadOnlyDictionary<string, string>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(await CreateStreamResultAsync(HttpStatusCode.OK, CreateBytes(16)));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockStreamingApiHttpClient.Received(1).GetStreamAsync(
|
||||
Arg.Any<string>(),
|
||||
Arg.Is<IReadOnlyDictionary<string, string>>(headers => headers.Count == 0),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteIdsAreNotParseable_ShouldForwardEmptyGuidsToTheApi()
|
||||
{
|
||||
// Arrange
|
||||
StreamMusicTrackRequest request = _streamMusicTrackRequestFixture.Create(artistId: "not-a-guid", albumId: "' OR '1'='1", trackId: "'; DROP TABLE Tracks; --");
|
||||
string expectedEndpoint = ApiRoutes.Music.STREAM_TRACK
|
||||
.Replace("{libraryId}", request.LibraryId.ToString())
|
||||
.Replace("{artistId}", Guid.Empty.ToString())
|
||||
.Replace("{albumId}", Guid.Empty.ToString())
|
||||
.Replace("{trackId}", Guid.Empty.ToString());
|
||||
_mockStreamingApiHttpClient.GetStreamAsync(Arg.Any<string>(), Arg.Any<IReadOnlyDictionary<string, string>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(await CreateStreamResultAsync(HttpStatusCode.OK, CreateBytes(8)));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockStreamingApiHttpClient.Received(1).GetStreamAsync(
|
||||
Arg.Is<string>(endpoint => endpoint == expectedEndpoint),
|
||||
Arg.Any<IReadOnlyDictionary<string, string>>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(HttpStatusCode.ServiceUnavailable)] // A busy normalization pipeline is a transient condition.
|
||||
[InlineData(HttpStatusCode.TooManyRequests)] // The stream concurrency limit was reached.
|
||||
public async Task ExecuteAsync_WhenApiReportsATransientCondition_ShouldReturnABareStatusWithoutThrowing(HttpStatusCode statusCode)
|
||||
{
|
||||
// Arrange
|
||||
StreamMusicTrackRequest request = _streamMusicTrackRequestFixture.Create();
|
||||
ApiException apiException = new(
|
||||
new ProblemDetailsDto { Title = "General.Failure", Detail = "InternalServerError", Status = (int)statusCode },
|
||||
statusCode,
|
||||
BuildExpectedEndpoint(request));
|
||||
_mockStreamingApiHttpClient.GetStreamAsync(Arg.Any<string>(), Arg.Any<IReadOnlyDictionary<string, string>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromException<ApiStreamResult>(apiException));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.IsType<EmptyHttpResult>(result);
|
||||
Assert.Equal((int)statusCode, _sut.HttpContext.Response.StatusCode);
|
||||
Assert.Equal(0, _sut.HttpContext.Response.ContentLength);
|
||||
Assert.Equal(0, _sut.HttpContext.Response.Body.Length);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReportsAnUnexpectedFailure_ShouldPropagateTheApiException()
|
||||
{
|
||||
// Arrange
|
||||
StreamMusicTrackRequest request = _streamMusicTrackRequestFixture.Create();
|
||||
ApiException apiException = new(
|
||||
new ProblemDetailsDto { Title = "General.Failure", Detail = "InternalServerError", Status = StatusCodes.Status500InternalServerError },
|
||||
HttpStatusCode.InternalServerError,
|
||||
BuildExpectedEndpoint(request));
|
||||
_mockStreamingApiHttpClient.GetStreamAsync(Arg.Any<string>(), Arg.Any<IReadOnlyDictionary<string, string>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromException<ApiStreamResult>(apiException));
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAsync<ApiException>(() => operationTask);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
StreamMusicTrackRequest request = _streamMusicTrackRequestFixture.Create();
|
||||
CancellationTokenSource cancellationTokenSource = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
_mockStreamingApiHttpClient.GetStreamAsync(Arg.Any<string>(), Arg.Any<IReadOnlyDictionary<string, string>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return await CreateStreamResultAsync(HttpStatusCode.OK, CreateBytes(8));
|
||||
}, callInfo.Arg<CancellationToken>()));
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(request, cancellationTokenSource.Token);
|
||||
await operationStarted.Task;
|
||||
cancellationTokenSource.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the upstream endpoint the track stream request is expected to be sent to.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to build the endpoint for.</param>
|
||||
/// <returns>The expected upstream endpoint.</returns>
|
||||
private static string BuildExpectedEndpoint(StreamMusicTrackRequest request)
|
||||
{
|
||||
return ApiRoutes.Music.STREAM_TRACK
|
||||
.Replace("{libraryId}", request.LibraryId.ToString())
|
||||
.Replace("{artistId}", request.ArtistId)
|
||||
.Replace("{albumId}", request.AlbumId)
|
||||
.Replace("{trackId}", request.TrackId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a streamed API response with a status code, a body and an optional media type.
|
||||
/// </summary>
|
||||
/// <param name="statusCode">The status code of the response.</param>
|
||||
/// <param name="contentBytes">The bytes of the content of the response.</param>
|
||||
/// <param name="contentType">The optional media type of the content.</param>
|
||||
/// <returns>The created streamed response.</returns>
|
||||
private static async Task<ApiStreamResult> CreateStreamResultAsync(HttpStatusCode statusCode, byte[] contentBytes, string? contentType = null)
|
||||
{
|
||||
HttpResponseMessage response = new(statusCode)
|
||||
{
|
||||
Content = new ByteArrayContent(contentBytes)
|
||||
};
|
||||
if (contentType is not null)
|
||||
response.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
|
||||
return await ApiStreamResult.CreateAsync(response, CancellationToken.None);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the bytes written to the response body of the provided HTTP context.
|
||||
/// </summary>
|
||||
/// <param name="httpContext">The HTTP context whose response body is read.</param>
|
||||
/// <returns>The bytes written to the response body.</returns>
|
||||
private static byte[] ReadResponseBody(HttpContext httpContext)
|
||||
{
|
||||
httpContext.Response.Body.Position = 0;
|
||||
using MemoryStream writtenBody = new();
|
||||
httpContext.Response.Body.CopyTo(writtenBody);
|
||||
return writtenBody.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a deterministic byte array that stands in for the content of a track.
|
||||
/// </summary>
|
||||
/// <param name="length">The number of bytes to create.</param>
|
||||
/// <returns>The created bytes.</returns>
|
||||
private static byte[] CreateBytes(int length)
|
||||
{
|
||||
return [.. Enumerable.Range(0, length).Select(index => (byte)(index % 256))];
|
||||
}
|
||||
}
|
||||
+265
@@ -0,0 +1,265 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.StreamMusicTrackSegment;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.StreamMusicTrackSegment;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="StreamMusicTrackSegmentEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class StreamMusicTrackSegmentEndpointTests
|
||||
{
|
||||
private readonly IStreamingApiHttpClient _mockStreamingApiHttpClient;
|
||||
private readonly StreamMusicTrackSegmentEndpoint _sut;
|
||||
private readonly StreamMusicTrackSegmentRequestFixture _streamMusicTrackSegmentRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="StreamMusicTrackSegmentEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public StreamMusicTrackSegmentEndpointTests()
|
||||
{
|
||||
_mockStreamingApiHttpClient = Substitute.For<IStreamingApiHttpClient>();
|
||||
_sut = Factory.Create<StreamMusicTrackSegmentEndpoint>(_mockStreamingApiHttpClient);
|
||||
_sut.HttpContext.Response.Body = new MemoryStream();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("uppercase")] // The handle format only accepts lowercase hexadecimal characters.
|
||||
[InlineData("dashed")] // The handle format is the N format of a GUID, without dashes.
|
||||
[InlineData("short")] // A handle that is shorter than the format allows.
|
||||
public async Task ExecuteAsync_WhenDeliveryIdIsInvalid_ShouldReturnNotFoundWithoutCallingTheApi(string malformedHandleKind)
|
||||
{
|
||||
// Arrange
|
||||
string validDeliveryId = Guid.NewGuid().ToString("N");
|
||||
string malformedDeliveryId = malformedHandleKind switch
|
||||
{
|
||||
"uppercase" => validDeliveryId.ToUpperInvariant(),
|
||||
"dashed" => Guid.Parse(validDeliveryId).ToString("D"),
|
||||
_ => validDeliveryId[..31],
|
||||
};
|
||||
StreamMusicTrackSegmentRequest request = _streamMusicTrackSegmentRequestFixture.Create(deliveryId: malformedDeliveryId);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.IsType<EmptyHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, _sut.HttpContext.Response.StatusCode);
|
||||
Assert.Equal(0, _sut.HttpContext.Response.ContentLength);
|
||||
Assert.Equal(0, _sut.HttpContext.Response.Body.Length);
|
||||
await _mockStreamingApiHttpClient.DidNotReceive().GetStreamAsync(
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<IReadOnlyDictionary<string, string>>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRequestIsValid_ShouldStreamTheSegmentFromTheApi()
|
||||
{
|
||||
// Arrange
|
||||
StreamMusicTrackSegmentRequest request = _streamMusicTrackSegmentRequestFixture.Create();
|
||||
string expectedEndpoint = BuildExpectedEndpoint(request);
|
||||
byte[] contentBytes = CreateBytes(512);
|
||||
ApiStreamResult streamResult = await CreateStreamResultAsync(HttpStatusCode.PartialContent, contentBytes, "audio/mp4");
|
||||
_mockStreamingApiHttpClient.GetStreamAsync(Arg.Any<string>(), Arg.Any<IReadOnlyDictionary<string, string>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(streamResult);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.IsType<EmptyHttpResult>(result);
|
||||
await _mockStreamingApiHttpClient.Received(1).GetStreamAsync(
|
||||
Arg.Is<string>(endpoint => endpoint == expectedEndpoint),
|
||||
Arg.Is<IReadOnlyDictionary<string, string>>(headers => headers.Count == 0),
|
||||
Arg.Any<CancellationToken>());
|
||||
Assert.Equal(StatusCodes.Status206PartialContent, _sut.HttpContext.Response.StatusCode);
|
||||
Assert.Equal("audio/mp4", _sut.HttpContext.Response.ContentType);
|
||||
Assert.Equal(contentBytes.Length, _sut.HttpContext.Response.ContentLength);
|
||||
Assert.Equal(contentBytes, ReadResponseBody(_sut.HttpContext));
|
||||
Assert.Equal("Cookie", _sut.HttpContext.Response.Headers["Vary"].ToString());
|
||||
Assert.Contains("private", _sut.HttpContext.Response.Headers["Cache-Control"].ToString());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("artistId", "' OR '1'='1")] // An unparseable artist Id is normalized to an empty GUID.
|
||||
[InlineData("albumId", "'; DROP TABLE Tracks; --")] // An unparseable album Id is normalized to an empty GUID.
|
||||
[InlineData("trackId", "not-a-guid")] // An unparseable track Id is normalized to an empty GUID.
|
||||
public async Task ExecuteAsync_WhenRouteIdsAreNotParseable_ShouldForwardEmptyGuidsToTheApi(string routeValue, string invalidValue)
|
||||
{
|
||||
// Arrange
|
||||
StreamMusicTrackSegmentRequest request = routeValue switch
|
||||
{
|
||||
"artistId" => _streamMusicTrackSegmentRequestFixture.Create(artistId: invalidValue),
|
||||
"albumId" => _streamMusicTrackSegmentRequestFixture.Create(albumId: invalidValue),
|
||||
_ => _streamMusicTrackSegmentRequestFixture.Create(trackId: invalidValue),
|
||||
};
|
||||
string expectedEndpoint = ApiRoutes.Music.STREAM_TRACK_SEGMENT
|
||||
.Replace("{libraryId}", request.LibraryId.ToString())
|
||||
.Replace("{artistId}", routeValue == "artistId" ? Guid.Empty.ToString() : request.ArtistId)
|
||||
.Replace("{albumId}", routeValue == "albumId" ? Guid.Empty.ToString() : request.AlbumId)
|
||||
.Replace("{trackId}", routeValue == "trackId" ? Guid.Empty.ToString() : request.TrackId)
|
||||
.Replace("{deliveryId}", request.DeliveryId)
|
||||
.Replace("{segmentIndex}", request.SegmentIndex.ToString(CultureInfo.InvariantCulture));
|
||||
_mockStreamingApiHttpClient.GetStreamAsync(Arg.Any<string>(), Arg.Any<IReadOnlyDictionary<string, string>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(await CreateStreamResultAsync(HttpStatusCode.OK, CreateBytes(8), "audio/mpeg"));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockStreamingApiHttpClient.Received(1).GetStreamAsync(
|
||||
Arg.Is<string>(endpoint => endpoint == expectedEndpoint),
|
||||
Arg.Any<IReadOnlyDictionary<string, string>>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(HttpStatusCode.ServiceUnavailable)] // A busy normalization pipeline is a transient condition.
|
||||
[InlineData(HttpStatusCode.TooManyRequests)] // The stream concurrency limit was reached.
|
||||
public async Task ExecuteAsync_WhenApiReportsATransientCondition_ShouldReturnABareStatusWithoutThrowing(HttpStatusCode statusCode)
|
||||
{
|
||||
// Arrange
|
||||
StreamMusicTrackSegmentRequest request = _streamMusicTrackSegmentRequestFixture.Create();
|
||||
ApiException apiException = new(
|
||||
new ProblemDetailsDto { Title = "General.Failure", Detail = "InternalServerError", Status = (int)statusCode },
|
||||
statusCode,
|
||||
BuildExpectedEndpoint(request));
|
||||
_mockStreamingApiHttpClient.GetStreamAsync(Arg.Any<string>(), Arg.Any<IReadOnlyDictionary<string, string>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromException<ApiStreamResult>(apiException));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.IsType<EmptyHttpResult>(result);
|
||||
Assert.Equal((int)statusCode, _sut.HttpContext.Response.StatusCode);
|
||||
Assert.Equal(0, _sut.HttpContext.Response.ContentLength);
|
||||
Assert.Equal(0, _sut.HttpContext.Response.Body.Length);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReportsAnUnexpectedFailure_ShouldPropagateTheApiException()
|
||||
{
|
||||
// Arrange
|
||||
StreamMusicTrackSegmentRequest request = _streamMusicTrackSegmentRequestFixture.Create();
|
||||
ApiException apiException = new(
|
||||
new ProblemDetailsDto { Title = "General.Failure", Detail = "InternalServerError", Status = StatusCodes.Status500InternalServerError },
|
||||
HttpStatusCode.InternalServerError,
|
||||
BuildExpectedEndpoint(request));
|
||||
_mockStreamingApiHttpClient.GetStreamAsync(Arg.Any<string>(), Arg.Any<IReadOnlyDictionary<string, string>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromException<ApiStreamResult>(apiException));
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAsync<ApiException>(() => operationTask);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
StreamMusicTrackSegmentRequest request = _streamMusicTrackSegmentRequestFixture.Create();
|
||||
CancellationTokenSource cancellationTokenSource = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
_mockStreamingApiHttpClient.GetStreamAsync(Arg.Any<string>(), Arg.Any<IReadOnlyDictionary<string, string>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return await CreateStreamResultAsync(HttpStatusCode.OK, CreateBytes(8));
|
||||
}, callInfo.Arg<CancellationToken>()));
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(request, cancellationTokenSource.Token);
|
||||
await operationStarted.Task;
|
||||
cancellationTokenSource.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the upstream endpoint the segment request is expected to be sent to.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to build the endpoint for.</param>
|
||||
/// <returns>The expected upstream endpoint.</returns>
|
||||
private static string BuildExpectedEndpoint(StreamMusicTrackSegmentRequest request)
|
||||
{
|
||||
return ApiRoutes.Music.STREAM_TRACK_SEGMENT
|
||||
.Replace("{libraryId}", request.LibraryId.ToString())
|
||||
.Replace("{artistId}", request.ArtistId)
|
||||
.Replace("{albumId}", request.AlbumId)
|
||||
.Replace("{trackId}", request.TrackId)
|
||||
.Replace("{deliveryId}", request.DeliveryId)
|
||||
.Replace("{segmentIndex}", request.SegmentIndex.ToString(CultureInfo.InvariantCulture));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a streamed API response with a status code, a body and an optional media type.
|
||||
/// </summary>
|
||||
/// <param name="statusCode">The status code of the response.</param>
|
||||
/// <param name="contentBytes">The bytes of the content of the response.</param>
|
||||
/// <param name="contentType">The optional media type of the content.</param>
|
||||
/// <returns>The created streamed response.</returns>
|
||||
private static async Task<ApiStreamResult> CreateStreamResultAsync(HttpStatusCode statusCode, byte[] contentBytes, string? contentType = null)
|
||||
{
|
||||
HttpResponseMessage response = new(statusCode)
|
||||
{
|
||||
Content = new ByteArrayContent(contentBytes)
|
||||
};
|
||||
if (contentType is not null)
|
||||
response.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
|
||||
return await ApiStreamResult.CreateAsync(response, CancellationToken.None);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the bytes written to the response body of the provided HTTP context.
|
||||
/// </summary>
|
||||
/// <param name="httpContext">The HTTP context whose response body is read.</param>
|
||||
/// <returns>The bytes written to the response body.</returns>
|
||||
private static byte[] ReadResponseBody(HttpContext httpContext)
|
||||
{
|
||||
httpContext.Response.Body.Position = 0;
|
||||
using MemoryStream writtenBody = new();
|
||||
httpContext.Response.Body.CopyTo(writtenBody);
|
||||
return writtenBody.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a deterministic byte array that stands in for the content of a segment.
|
||||
/// </summary>
|
||||
/// <param name="length">The number of bytes to create.</param>
|
||||
/// <returns>The created bytes.</returns>
|
||||
private static byte[] CreateBytes(int length)
|
||||
{
|
||||
return [.. Enumerable.Range(0, length).Select(index => (byte)(index % 256))];
|
||||
}
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.Management;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.DeleteLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Management;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.Management.DeleteLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="DeleteLibraryEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteLibraryEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly DeleteLibraryEndpoint _sut;
|
||||
private readonly DeleteLibraryRequestFixture _deleteLibraryRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteLibraryEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public DeleteLibraryEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<DeleteLibraryEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldDeleteLibraryViaApiAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
DeleteLibraryRequest request = _deleteLibraryRequestFixture.Create();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
string expectedEndpoint = ApiRoutes.Libraries.DELETE_LIBRARY.Replace("{id}", request.Id.ToString());
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(expectedEndpoint, Arg.Any<CancellationToken>());
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
}
|
||||
}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.Plugins;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.Management;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetBookReaders;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Management;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.Management.GetBookReaders;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetBookReadersEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetBookReadersEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly GetBookReadersEndpoint _sut;
|
||||
private readonly GetBookReadersRequestFixture _getBookReadersRequestFixture = new();
|
||||
private readonly LibraryBookReaderDtoFixture _libraryBookReaderDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetBookReadersEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetBookReadersEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<GetBookReadersEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnSuccessJsonWithBookReaders()
|
||||
{
|
||||
// Arrange
|
||||
GetBookReadersRequest request = _getBookReadersRequestFixture.Create();
|
||||
LibraryBookReaderDto[] readers = [.. _libraryBookReaderDtoFixture.CreateMany(2)];
|
||||
_mockApiHttpClient.GetAsync<LibraryBookReaderDto[]>(ApiRoutes.Libraries.GET_LIBRARY_BOOK_READERS.Replace("{libraryId}", request.LibraryId.ToString()), Arg.Any<CancellationToken>())
|
||||
.Returns(readers);
|
||||
|
||||
// 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());
|
||||
Assert.Equal(readers.Length, jsonDocument.RootElement.GetProperty("data").GetArrayLength());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldRequestBookReadersFromApi()
|
||||
{
|
||||
// Arrange
|
||||
GetBookReadersRequest request = _getBookReadersRequestFixture.Create();
|
||||
LibraryBookReaderDto[] readers = [.. _libraryBookReaderDtoFixture.CreateMany(2)];
|
||||
_mockApiHttpClient.GetAsync<LibraryBookReaderDto[]>(ApiRoutes.Libraries.GET_LIBRARY_BOOK_READERS.Replace("{libraryId}", request.LibraryId.ToString()), Arg.Any<CancellationToken>())
|
||||
.Returns(readers);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<LibraryBookReaderDto[]>(ApiRoutes.Libraries.GET_LIBRARY_BOOK_READERS.Replace("{libraryId}", request.LibraryId.ToString()), Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraries;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
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.Library.Management.GetLibraries;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetLibrariesEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetLibrariesEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly GetLibrariesEndpoint _sut;
|
||||
private readonly LibraryDtoFixture _libraryDtoFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetLibrariesEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetLibrariesEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<GetLibrariesEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsLibraries_ShouldReturnSuccessJsonWithLibraries()
|
||||
{
|
||||
// Arrange
|
||||
LibraryDto[] expectedLibraries = [.. _libraryDtoFixture.CreateMany(2)];
|
||||
_mockApiHttpClient.GetAsync<LibraryDto[]>(ApiRoutes.Libraries.GET_LIBRARIES, Arg.Any<CancellationToken>())
|
||||
.Returns(expectedLibraries);
|
||||
|
||||
// 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());
|
||||
LibraryDto[]? returnedLibraries = jsonDocument.RootElement.GetProperty("data").Deserialize<LibraryDto[]>(_jsonOptions);
|
||||
Assert.Equal(expectedLibraries.Select(library => library.Title), returnedLibraries!.Select(library => library.Title));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldRequestLibrariesFromApi()
|
||||
{
|
||||
// Arrange
|
||||
_mockApiHttpClient.GetAsync<LibraryDto[]>(ApiRoutes.Libraries.GET_LIBRARIES, Arg.Any<CancellationToken>())
|
||||
.Returns([.. _libraryDtoFixture.CreateMany(2)]);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<LibraryDto[]>(ApiRoutes.Libraries.GET_LIBRARIES, Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+113
@@ -0,0 +1,113 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.Management;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryPathTemplateParts;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Management;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.Management.GetLibraryPathTemplateParts;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetLibraryPathTemplatePartsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetLibraryPathTemplatePartsEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly GetLibraryPathTemplatePartsEndpoint _sut;
|
||||
private readonly GetLibraryPathTemplatePartsRequestFixture _getLibraryPathTemplatePartsRequestFixture = new();
|
||||
private readonly LibraryPathTemplateCatalogDtoFixture _libraryPathTemplateCatalogDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetLibraryPathTemplatePartsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetLibraryPathTemplatePartsEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<GetLibraryPathTemplatePartsEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnSuccessJsonWithCatalog()
|
||||
{
|
||||
// Arrange
|
||||
GetLibraryPathTemplatePartsRequest request = _getLibraryPathTemplatePartsRequestFixture.Create();
|
||||
LibraryPathTemplateCatalogDto catalog = _libraryPathTemplateCatalogDtoFixture.Create();
|
||||
_mockApiHttpClient.GetAsync<LibraryPathTemplateCatalogDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(catalog);
|
||||
|
||||
// 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");
|
||||
JsonElement parts = data.GetProperty("parts");
|
||||
JsonElement defaultTemplateParts = data.GetProperty("defaultTemplateParts");
|
||||
Assert.Equal(catalog.Parts.Count, parts.GetArrayLength());
|
||||
Assert.Equal(catalog.DefaultTemplateParts.Count, defaultTemplateParts.GetArrayLength());
|
||||
|
||||
JsonElement firstPart = parts[0];
|
||||
Assert.Equal(catalog.Parts[0].Kind, firstPart.GetProperty("kind").GetString());
|
||||
Assert.Equal(catalog.Parts[0].ValueType, firstPart.GetProperty("valueType").GetString());
|
||||
Assert.Equal(catalog.Parts[0].DefaultRepresentation, firstPart.GetProperty("defaultRepresentation").GetString());
|
||||
Assert.Equal(catalog.Parts[0].IsOptionalByDefault, firstPart.GetProperty("isOptionalByDefault").GetBoolean());
|
||||
|
||||
JsonElement firstDefaultTemplatePart = defaultTemplateParts[0];
|
||||
Assert.Equal(catalog.DefaultTemplateParts[0].Kind, firstDefaultTemplatePart.GetProperty("kind").GetString());
|
||||
Assert.Equal(catalog.DefaultTemplateParts[0].Representation, firstDefaultTemplatePart.GetProperty("representation").GetString());
|
||||
Assert.Equal(catalog.DefaultTemplateParts[0].IsOptional, firstDefaultTemplatePart.GetProperty("isOptional").GetBoolean());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldRequestCatalogFromApiWithSubstitutedLibraryType()
|
||||
{
|
||||
// Arrange
|
||||
GetLibraryPathTemplatePartsRequest request = _getLibraryPathTemplatePartsRequestFixture.Create(libraryType: "Music");
|
||||
LibraryPathTemplateCatalogDto catalog = _libraryPathTemplateCatalogDtoFixture.Create();
|
||||
_mockApiHttpClient.GetAsync<LibraryPathTemplateCatalogDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(catalog);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<LibraryPathTemplateCatalogDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Libraries.GET_LIBRARY_PATH_TEMPLATE_PARTS.Replace("{libraryType}", "Music")),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldForwardCancellationTokenToApi()
|
||||
{
|
||||
// Arrange
|
||||
GetLibraryPathTemplatePartsRequest request = _getLibraryPathTemplatePartsRequestFixture.Create();
|
||||
LibraryPathTemplateCatalogDto catalog = _libraryPathTemplateCatalogDtoFixture.Create();
|
||||
CancellationTokenSource cancellationTokenSource = new();
|
||||
CancellationToken cancellationToken = cancellationTokenSource.Token;
|
||||
_mockApiHttpClient.GetAsync<LibraryPathTemplateCatalogDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(catalog);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<LibraryPathTemplateCatalogDto>(
|
||||
Arg.Any<string>(),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
}
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.Plugins;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.Management;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryTypeArtworkProviders;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Management;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.Management.GetLibraryTypeArtworkProviders;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetLibraryTypeArtworkProvidersEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetLibraryTypeArtworkProvidersEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly GetLibraryTypeArtworkProvidersEndpoint _sut;
|
||||
private readonly GetLibraryTypeArtworkProvidersRequestFixture _getLibraryTypeArtworkProvidersRequestFixture = new();
|
||||
private readonly LibraryArtworkProviderDtoFixture _libraryArtworkProviderDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetLibraryTypeArtworkProvidersEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetLibraryTypeArtworkProvidersEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<GetLibraryTypeArtworkProvidersEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnSuccessJsonWithTheProviders()
|
||||
{
|
||||
// Arrange
|
||||
GetLibraryTypeArtworkProvidersRequest request = _getLibraryTypeArtworkProvidersRequestFixture.Create();
|
||||
LibraryArtworkProviderDto[] providers = [.. _libraryArtworkProviderDtoFixture.CreateMany(2)];
|
||||
_mockApiHttpClient.GetAsync<LibraryArtworkProviderDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(providers);
|
||||
|
||||
// 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(providers.Length, data.GetArrayLength());
|
||||
Assert.Equal(providers[0].PluginId, data[0].GetProperty("pluginId").GetGuid());
|
||||
Assert.Equal(providers[0].Name, data[0].GetProperty("name").GetString());
|
||||
Assert.Equal(providers[0].IsEnabled, data[0].GetProperty("isEnabled").GetBoolean());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldRequestTheProvidersFromApiWithSubstitutedLibraryType()
|
||||
{
|
||||
// Arrange
|
||||
GetLibraryTypeArtworkProvidersRequest request = _getLibraryTypeArtworkProvidersRequestFixture.Create(libraryType: "Music");
|
||||
_mockApiHttpClient.GetAsync<LibraryArtworkProviderDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns([]);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<LibraryArtworkProviderDto[]>(
|
||||
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Libraries.GET_LIBRARY_TYPE_ARTWORK_PROVIDERS.Replace("{libraryType}", "Music")),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenLibraryTypeContainsPathCharacters_ShouldEscapeItInTheApiRoute()
|
||||
{
|
||||
// Arrange
|
||||
GetLibraryTypeArtworkProvidersRequest request = _getLibraryTypeArtworkProvidersRequestFixture.Create(libraryType: "../plugins");
|
||||
_mockApiHttpClient.GetAsync<LibraryArtworkProviderDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns([]);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<LibraryArtworkProviderDto[]>(
|
||||
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Libraries.GET_LIBRARY_TYPE_ARTWORK_PROVIDERS.Replace("{libraryType}", Uri.EscapeDataString("../plugins"))),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldForwardCancellationTokenToApi()
|
||||
{
|
||||
// Arrange
|
||||
GetLibraryTypeArtworkProvidersRequest request = _getLibraryTypeArtworkProvidersRequestFixture.Create();
|
||||
CancellationTokenSource cancellationTokenSource = new();
|
||||
CancellationToken cancellationToken = cancellationTokenSource.Token;
|
||||
_mockApiHttpClient.GetAsync<LibraryArtworkProviderDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns([]);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<LibraryArtworkProviderDto[]>(
|
||||
Arg.Any<string>(),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
}
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.Plugins;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.Management;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryTypeBookReaders;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Management;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.Management.GetLibraryTypeBookReaders;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetLibraryTypeBookReadersEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetLibraryTypeBookReadersEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly GetLibraryTypeBookReadersEndpoint _sut;
|
||||
private readonly GetLibraryTypeBookReadersRequestFixture _getLibraryTypeBookReadersRequestFixture = new();
|
||||
private readonly LibraryBookReaderDtoFixture _libraryBookReaderDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetLibraryTypeBookReadersEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetLibraryTypeBookReadersEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<GetLibraryTypeBookReadersEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnSuccessJsonWithTheReaders()
|
||||
{
|
||||
// Arrange
|
||||
GetLibraryTypeBookReadersRequest request = _getLibraryTypeBookReadersRequestFixture.Create();
|
||||
LibraryBookReaderDto[] readers = [.. _libraryBookReaderDtoFixture.CreateMany(2)];
|
||||
_mockApiHttpClient.GetAsync<LibraryBookReaderDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(readers);
|
||||
|
||||
// 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(readers.Length, data.GetArrayLength());
|
||||
Assert.Equal(readers[0].PluginId, data[0].GetProperty("pluginId").GetGuid());
|
||||
Assert.Equal(readers[0].Name, data[0].GetProperty("name").GetString());
|
||||
Assert.Equal(readers[0].IsEnabled, data[0].GetProperty("isEnabled").GetBoolean());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldRequestTheReadersFromApiWithSubstitutedLibraryType()
|
||||
{
|
||||
// Arrange
|
||||
GetLibraryTypeBookReadersRequest request = _getLibraryTypeBookReadersRequestFixture.Create(libraryType: "Music");
|
||||
_mockApiHttpClient.GetAsync<LibraryBookReaderDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns([]);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<LibraryBookReaderDto[]>(
|
||||
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Libraries.GET_LIBRARY_TYPE_BOOK_READERS.Replace("{libraryType}", "Music")),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenLibraryTypeContainsPathCharacters_ShouldEscapeItInTheApiRoute()
|
||||
{
|
||||
// Arrange
|
||||
GetLibraryTypeBookReadersRequest request = _getLibraryTypeBookReadersRequestFixture.Create(libraryType: "../plugins");
|
||||
_mockApiHttpClient.GetAsync<LibraryBookReaderDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns([]);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<LibraryBookReaderDto[]>(
|
||||
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Libraries.GET_LIBRARY_TYPE_BOOK_READERS.Replace("{libraryType}", Uri.EscapeDataString("../plugins"))),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldForwardCancellationTokenToApi()
|
||||
{
|
||||
// Arrange
|
||||
GetLibraryTypeBookReadersRequest request = _getLibraryTypeBookReadersRequestFixture.Create();
|
||||
CancellationTokenSource cancellationTokenSource = new();
|
||||
CancellationToken cancellationToken = cancellationTokenSource.Token;
|
||||
_mockApiHttpClient.GetAsync<LibraryBookReaderDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns([]);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<LibraryBookReaderDto[]>(
|
||||
Arg.Any<string>(),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
}
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.Plugins;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.Management;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryTypeMetadataProviders;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Management;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.Management.GetLibraryTypeMetadataProviders;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetLibraryTypeMetadataProvidersEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetLibraryTypeMetadataProvidersEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly GetLibraryTypeMetadataProvidersEndpoint _sut;
|
||||
private readonly GetLibraryTypeMetadataProvidersRequestFixture _getLibraryTypeMetadataProvidersRequestFixture = new();
|
||||
private readonly LibraryMetadataProviderDtoFixture _libraryMetadataProviderDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetLibraryTypeMetadataProvidersEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetLibraryTypeMetadataProvidersEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<GetLibraryTypeMetadataProvidersEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnSuccessJsonWithTheProviders()
|
||||
{
|
||||
// Arrange
|
||||
GetLibraryTypeMetadataProvidersRequest request = _getLibraryTypeMetadataProvidersRequestFixture.Create();
|
||||
LibraryMetadataProviderDto[] providers = [.. _libraryMetadataProviderDtoFixture.CreateMany(2)];
|
||||
_mockApiHttpClient.GetAsync<LibraryMetadataProviderDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(providers);
|
||||
|
||||
// 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(providers.Length, data.GetArrayLength());
|
||||
Assert.Equal(providers[0].PluginId, data[0].GetProperty("pluginId").GetGuid());
|
||||
Assert.Equal(providers[0].Name, data[0].GetProperty("name").GetString());
|
||||
Assert.Equal(providers[0].IsEnabled, data[0].GetProperty("isEnabled").GetBoolean());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldRequestTheProvidersFromApiWithSubstitutedLibraryType()
|
||||
{
|
||||
// Arrange
|
||||
GetLibraryTypeMetadataProvidersRequest request = _getLibraryTypeMetadataProvidersRequestFixture.Create(libraryType: "Music");
|
||||
_mockApiHttpClient.GetAsync<LibraryMetadataProviderDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns([]);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<LibraryMetadataProviderDto[]>(
|
||||
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Libraries.GET_LIBRARY_TYPE_METADATA_PROVIDERS.Replace("{libraryType}", "Music")),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenLibraryTypeContainsPathCharacters_ShouldEscapeItInTheApiRoute()
|
||||
{
|
||||
// Arrange
|
||||
GetLibraryTypeMetadataProvidersRequest request = _getLibraryTypeMetadataProvidersRequestFixture.Create(libraryType: "../plugins");
|
||||
_mockApiHttpClient.GetAsync<LibraryMetadataProviderDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns([]);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<LibraryMetadataProviderDto[]>(
|
||||
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Libraries.GET_LIBRARY_TYPE_METADATA_PROVIDERS.Replace("{libraryType}", Uri.EscapeDataString("../plugins"))),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldForwardCancellationTokenToApi()
|
||||
{
|
||||
// Arrange
|
||||
GetLibraryTypeMetadataProvidersRequest request = _getLibraryTypeMetadataProvidersRequestFixture.Create();
|
||||
CancellationTokenSource cancellationTokenSource = new();
|
||||
CancellationToken cancellationToken = cancellationTokenSource.Token;
|
||||
_mockApiHttpClient.GetAsync<LibraryMetadataProviderDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns([]);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<LibraryMetadataProviderDto[]>(
|
||||
Arg.Any<string>(),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
}
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Authorization;
|
||||
using Lumina.Presentation.Web.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Common.Enums.Authorization;
|
||||
using Lumina.Presentation.Web.Common.Http;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.Index;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Reflection;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.Management.Index;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="LibrariesIndexViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LibrariesIndexViewEndpointTests
|
||||
{
|
||||
private readonly IAuthorizationService _mockAuthorizationService;
|
||||
private readonly LibrariesIndexViewEndpoint _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LibrariesIndexViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public LibrariesIndexViewEndpointTests()
|
||||
{
|
||||
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
|
||||
_sut = Factory.Create<LibrariesIndexViewEndpoint>(_mockAuthorizationService);
|
||||
TestHttpContextFactory.ConfigureSession(_sut.HttpContext, TestHttpContextFactory.CreateSession());
|
||||
_sut.HttpContext.Request.Path = "/en-us/libraries/manage";
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenTheUserHoldsTheManagePermission_ShouldRenderTheIndexViewWithManagementAllowed()
|
||||
{
|
||||
// Arrange
|
||||
_mockAuthorizationService.IsInRoleAsync("Admin", Arg.Any<CancellationToken>()).Returns(false);
|
||||
_mockAuthorizationService.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, Arg.Any<CancellationToken>()).Returns(true);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("/Core/Views/Library/Management/Index.cshtml", GetRenderedViewName(result));
|
||||
LibrariesIndexPageDto model = Assert.IsType<LibrariesIndexPageDto>(GetRenderedModel(result));
|
||||
Assert.True(model.CanManageLibraries);
|
||||
await _mockAuthorizationService.Received(1).IsInRoleAsync("Admin", Arg.Any<CancellationToken>());
|
||||
await _mockAuthorizationService.Received(1).HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenTheUserIsAnAdministratorWithoutTheManagePermission_ShouldRenderTheIndexViewWithManagementAllowed()
|
||||
{
|
||||
// Arrange
|
||||
_mockAuthorizationService.IsInRoleAsync("Admin", Arg.Any<CancellationToken>()).Returns(true);
|
||||
_mockAuthorizationService.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, Arg.Any<CancellationToken>()).Returns(false);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("/Core/Views/Library/Management/Index.cshtml", GetRenderedViewName(result));
|
||||
LibrariesIndexPageDto model = Assert.IsType<LibrariesIndexPageDto>(GetRenderedModel(result));
|
||||
Assert.True(model.CanManageLibraries);
|
||||
await _mockAuthorizationService.DidNotReceive().HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenTheUserIsNeitherAnAdministratorNorHoldsTheManagePermission_ShouldRenderTheIndexViewWithManagementDenied()
|
||||
{
|
||||
// Arrange
|
||||
_mockAuthorizationService.IsInRoleAsync("Admin", Arg.Any<CancellationToken>()).Returns(false);
|
||||
_mockAuthorizationService.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, Arg.Any<CancellationToken>()).Returns(false);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("/Core/Views/Library/Management/Index.cshtml", GetRenderedViewName(result));
|
||||
LibrariesIndexPageDto model = Assert.IsType<LibrariesIndexPageDto>(GetRenderedModel(result));
|
||||
Assert.False(model.CanManageLibraries);
|
||||
}
|
||||
|
||||
/// <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);
|
||||
}
|
||||
}
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.SaveLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.Management.SaveLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="SaveLibraryEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SaveLibraryEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly SaveLibraryEndpoint _sut;
|
||||
private readonly LibraryDtoFixture _libraryDtoFixture = new();
|
||||
private readonly LibraryProviderSelectionDtoFixture _libraryProviderSelectionDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SaveLibraryEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public SaveLibraryEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<SaveLibraryEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRequestHasId_ShouldUpdateLibraryViaApi()
|
||||
{
|
||||
// Arrange
|
||||
LibraryDto request = _libraryDtoFixture.Create();
|
||||
LibraryDto expectedResponse = _libraryDtoFixture.Create(id: request.Id);
|
||||
_mockApiHttpClient.PutAsync<LibraryDto, LibraryDto>(Arg.Any<string>(), Arg.Any<LibraryDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedResponse);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
string expectedEndpoint = ApiRoutes.Libraries.UPDATE_LIBRARY.Replace("{id}", request.Id!.Value.ToString());
|
||||
await _mockApiHttpClient.Received(1).PutAsync<LibraryDto, LibraryDto>(expectedEndpoint, Arg.Is<LibraryDto>(library => library.Title == request.Title), Arg.Any<CancellationToken>());
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRequestHasNoId_ShouldCreateLibraryViaApi()
|
||||
{
|
||||
// Arrange
|
||||
LibraryDto request = _libraryDtoFixture.Create();
|
||||
request.Id = null;
|
||||
LibraryDto expectedResponse = _libraryDtoFixture.Create(id: request.Id);
|
||||
_mockApiHttpClient.PostAsync<LibraryDto, LibraryDto>(Arg.Any<string>(), Arg.Any<LibraryDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedResponse);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostAsync<LibraryDto, LibraryDto>(ApiRoutes.Libraries.ADD_LIBRARY, Arg.Is<LibraryDto>(library => library.Title == request.Title), Arg.Any<CancellationToken>());
|
||||
await _mockApiHttpClient.DidNotReceive().PutAsync<LibraryDto, LibraryDto>(Arg.Any<string>(), Arg.Any<LibraryDto>(), Arg.Any<CancellationToken>());
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenProviderChoicesAreMade_ShouldForwardThemToTheApi()
|
||||
{
|
||||
// Arrange
|
||||
LibraryDto request = _libraryDtoFixture.Create();
|
||||
request.Id = null;
|
||||
request.MetadataProviders = _libraryProviderSelectionDtoFixture.CreateMany(2);
|
||||
request.ArtworkProviders = [];
|
||||
request.BookReaders = null;
|
||||
_mockApiHttpClient.PostAsync<LibraryDto, LibraryDto>(Arg.Any<string>(), Arg.Any<LibraryDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_libraryDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostAsync<LibraryDto, LibraryDto>(
|
||||
ApiRoutes.Libraries.ADD_LIBRARY,
|
||||
Arg.Is<LibraryDto>(library =>
|
||||
library.MetadataProviders == request.MetadataProviders &&
|
||||
library.ArtworkProviders == request.ArtworkProviders &&
|
||||
library.BookReaders == null),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.Statistics;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.ClearConsumptionHistory;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Statistics;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.Statistics.ClearConsumptionHistory;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ClearConsumptionHistoryEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ClearConsumptionHistoryEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly ClearConsumptionHistoryEndpoint _sut;
|
||||
private readonly ClearConsumptionHistoryRequestFixture _clearConsumptionHistoryRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ClearConsumptionHistoryEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public ClearConsumptionHistoryEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_mockApiHttpClient.DeleteAsync(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
|
||||
_sut = Factory.Create<ClearConsumptionHistoryEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiSucceeds_ShouldReturnSuccessJsonWithoutData()
|
||||
{
|
||||
// Arrange
|
||||
ClearConsumptionHistoryRequest request = _clearConsumptionHistoryRequestFixture.Create();
|
||||
|
||||
// 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());
|
||||
Assert.False(jsonDocument.RootElement.TryGetProperty("data", out _));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // No user selected, the current user is implied.
|
||||
[InlineData("")] // Empty user selected.
|
||||
[InlineData(" ")] // Whitespace user selected.
|
||||
public async Task ExecuteAsync_WhenUserIdIsNullOrWhitespace_ShouldDeleteCurrentUserHistory(string? userId)
|
||||
{
|
||||
// Arrange
|
||||
ClearConsumptionHistoryRequest request = _clearConsumptionHistoryRequestFixture.Create(userId: userId, includeUserId: userId is not null);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
Arg.Is<string>(endpoint => endpoint == ApiRoutes.LibraryStatistics.CLEAR_CONSUMPTION_HISTORY),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenUserIdIsSet_ShouldRequestUserHistoryWithEscapedUserId()
|
||||
{
|
||||
// Arrange
|
||||
ClearConsumptionHistoryRequest request = _clearConsumptionHistoryRequestFixture.Create(userId: "user/../admin?x=1&y=2");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/user%2F..%2Fadmin%3Fx%3D1%26y%3D2/consumption-history"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSetPrivateNoStoreAndCookieVaryHeaders()
|
||||
{
|
||||
// Arrange
|
||||
ClearConsumptionHistoryRequest request = _clearConsumptionHistoryRequestFixture.Create();
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString());
|
||||
Assert.Equal("Cookie", _sut.HttpContext.Response.Headers["Vary"].ToString());
|
||||
}
|
||||
}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.Statistics;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.ClearResumePoints;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Statistics;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.Statistics.ClearResumePoints;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ClearResumePointsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ClearResumePointsEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly ClearResumePointsEndpoint _sut;
|
||||
private readonly ClearResumePointsRequestFixture _clearResumePointsRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ClearResumePointsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public ClearResumePointsEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_mockApiHttpClient.DeleteAsync(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
|
||||
_sut = Factory.Create<ClearResumePointsEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiSucceeds_ShouldReturnSuccessJsonWithoutData()
|
||||
{
|
||||
// Arrange
|
||||
ClearResumePointsRequest request = _clearResumePointsRequestFixture.Create();
|
||||
|
||||
// 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());
|
||||
Assert.False(jsonDocument.RootElement.TryGetProperty("data", out _));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // No user selected, the current user is implied.
|
||||
[InlineData("")] // Empty user selected.
|
||||
[InlineData(" ")] // Whitespace user selected.
|
||||
public async Task ExecuteAsync_WhenUserIdIsNullOrWhitespaceAndLibraryIdIsNull_ShouldClearCurrentUserResumePointsWithoutFilter(string? userId)
|
||||
{
|
||||
// Arrange
|
||||
ClearResumePointsRequest request = _clearResumePointsRequestFixture.Create(
|
||||
userId: userId,
|
||||
includeUserId: userId is not null,
|
||||
includeLibraryId: false);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
Arg.Is<string>(endpoint => endpoint == ApiRoutes.LibraryStatistics.CLEAR_RESUME_POINTS),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOnlyLibraryIdIsSet_ShouldAppendEscapedLibraryFilterToCurrentUserRoute()
|
||||
{
|
||||
// Arrange
|
||||
ClearResumePointsRequest request = _clearResumePointsRequestFixture.Create(
|
||||
libraryId: "lib?x=1&y=2",
|
||||
includeUserId: false);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/me/media-resume-points?libraryId=lib%3Fx%3D1%26y%3D2"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenUserIdAndLibraryIdAreSet_ShouldRequestUserRouteWithBothValuesEscaped()
|
||||
{
|
||||
// Arrange
|
||||
ClearResumePointsRequest request = _clearResumePointsRequestFixture.Create(
|
||||
userId: "user/../admin?x=1&y=2",
|
||||
libraryId: "lib?x=1&y=2");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/user%2F..%2Fadmin%3Fx%3D1%26y%3D2/media-resume-points?libraryId=lib%3Fx%3D1%26y%3D2"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSetPrivateNoStoreAndCookieVaryHeaders()
|
||||
{
|
||||
// Arrange
|
||||
ClearResumePointsRequest request = _clearResumePointsRequestFixture.Create();
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString());
|
||||
Assert.Equal("Cookie", _sut.HttpContext.Response.Headers["Vary"].ToString());
|
||||
}
|
||||
}
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.Enums.MediaConsumption;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.Statistics;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.DeleteConsumptionItemHistory;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Statistics;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.Statistics.DeleteConsumptionItemHistory;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="DeleteConsumptionItemHistoryEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteConsumptionItemHistoryEndpointTests
|
||||
{
|
||||
private static readonly Guid s_mediaItemId = Guid.Parse("11111111-1111-1111-1111-111111111111");
|
||||
private static readonly Guid s_libraryId = Guid.Parse("22222222-2222-2222-2222-222222222222");
|
||||
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly DeleteConsumptionItemHistoryEndpoint _sut;
|
||||
private readonly DeleteConsumptionItemHistoryRequestFixture _deleteConsumptionItemHistoryRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteConsumptionItemHistoryEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public DeleteConsumptionItemHistoryEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_mockApiHttpClient.DeleteAsync(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
|
||||
_sut = Factory.Create<DeleteConsumptionItemHistoryEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiSucceeds_ShouldReturnSuccessJsonWithoutData()
|
||||
{
|
||||
// Arrange
|
||||
DeleteConsumptionItemHistoryRequest request = _deleteConsumptionItemHistoryRequestFixture.Create();
|
||||
|
||||
// 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());
|
||||
Assert.False(jsonDocument.RootElement.TryGetProperty("data", out _));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // No user selected, the current user is implied.
|
||||
[InlineData("")] // Empty user selected.
|
||||
[InlineData(" ")] // Whitespace user selected.
|
||||
public async Task ExecuteAsync_WhenUserIdIsNullOrWhitespace_ShouldDeleteCurrentUserItemHistory(string? userId)
|
||||
{
|
||||
// Arrange
|
||||
DeleteConsumptionItemHistoryRequest request = _deleteConsumptionItemHistoryRequestFixture.Create(
|
||||
userId: userId,
|
||||
includeUserId: userId is not null,
|
||||
mediaKind: MediaKind.Movie,
|
||||
mediaItemId: s_mediaItemId,
|
||||
libraryId: s_libraryId);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/me/consumption-history/media-items/Movie/11111111-1111-1111-1111-111111111111/22222222-2222-2222-2222-222222222222"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(MediaKind.MusicTrack, "MusicTrack")] // A music track.
|
||||
[InlineData(MediaKind.PodcastEpisode, "PodcastEpisode")] // A podcast episode.
|
||||
[InlineData(MediaKind.Book, "Book")] // A book.
|
||||
public async Task ExecuteAsync_WhenMediaKindIsSet_ShouldUseTheMediaKindNameInTheUpstreamRoute(MediaKind mediaKind, string expectedMediaKind)
|
||||
{
|
||||
// Arrange
|
||||
DeleteConsumptionItemHistoryRequest request = _deleteConsumptionItemHistoryRequestFixture.Create(
|
||||
mediaKind: mediaKind,
|
||||
mediaItemId: s_mediaItemId,
|
||||
libraryId: s_libraryId,
|
||||
includeUserId: false);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
Arg.Is<string>(endpoint => endpoint == $"users/me/consumption-history/media-items/{expectedMediaKind}/11111111-1111-1111-1111-111111111111/22222222-2222-2222-2222-222222222222"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenUserIdIsSet_ShouldRequestUserRouteWithEscapedUserId()
|
||||
{
|
||||
// Arrange
|
||||
DeleteConsumptionItemHistoryRequest request = _deleteConsumptionItemHistoryRequestFixture.Create(
|
||||
userId: "user/../admin?x=1&y=2",
|
||||
mediaKind: MediaKind.Book,
|
||||
mediaItemId: s_mediaItemId,
|
||||
libraryId: s_libraryId);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/user%2F..%2Fadmin%3Fx%3D1%26y%3D2/consumption-history/media-items/Book/11111111-1111-1111-1111-111111111111/22222222-2222-2222-2222-222222222222"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSetPrivateNoStoreAndCookieVaryHeaders()
|
||||
{
|
||||
// Arrange
|
||||
DeleteConsumptionItemHistoryRequest request = _deleteConsumptionItemHistoryRequestFixture.Create();
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString());
|
||||
Assert.Equal("Cookie", _sut.HttpContext.Response.Headers["Vary"].ToString());
|
||||
}
|
||||
}
|
||||
+249
@@ -0,0 +1,249 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.Authorization;
|
||||
using Lumina.Presentation.Web.Common.DTO.MediaConsumption;
|
||||
using Lumina.Presentation.Web.Common.Enums.MediaConsumption;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.Statistics;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetAllUsersConsumptionStatistics;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.MediaConsumption;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Statistics;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
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.Library.Statistics.GetAllUsersConsumptionStatistics;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetAllUsersConsumptionStatisticsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetAllUsersConsumptionStatisticsEndpointTests
|
||||
{
|
||||
private static readonly DateTime s_fromUtc = new(2024, 3, 4, 5, 6, 7, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_toUtc = new(2025, 6, 7, 8, 9, 10, DateTimeKind.Utc);
|
||||
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly GetAllUsersConsumptionStatisticsEndpoint _sut;
|
||||
private readonly GetAllUsersConsumptionStatisticsRequestFixture _getAllUsersConsumptionStatisticsRequestFixture = new();
|
||||
private readonly AllUsersConsumptionStatisticsDtoFixture _allUsersConsumptionStatisticsDtoFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetAllUsersConsumptionStatisticsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetAllUsersConsumptionStatisticsEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<GetAllUsersConsumptionStatisticsEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsStatistics_ShouldReturnSuccessJsonWithStatistics()
|
||||
{
|
||||
// Arrange
|
||||
AllUsersConsumptionStatisticsDto expectedStatistics = _allUsersConsumptionStatisticsDtoFixture.Create();
|
||||
_mockApiHttpClient.GetAsync<AllUsersConsumptionStatisticsDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedStatistics);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(
|
||||
_getAllUsersConsumptionStatisticsRequestFixture.Create(includeLibraryId: false, includeMediaKind: false, includeFromUtc: false, includeToUtc: false),
|
||||
CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
AllUsersConsumptionStatisticsDto? returnedStatistics = jsonDocument.RootElement.GetProperty("data").Deserialize<AllUsersConsumptionStatisticsDto>(_jsonOptions);
|
||||
Assert.NotNull(returnedStatistics);
|
||||
Assert.Equal(expectedStatistics.Total.CountedSessionCount, returnedStatistics.Total.CountedSessionCount);
|
||||
Assert.Equal(
|
||||
expectedStatistics.Users.Select(userStatistics => userStatistics.UserId),
|
||||
returnedStatistics.Users.Select(userStatistics => userStatistics.UserId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenNoFilterIsSupplied_ShouldRequestAllUsersStatisticsWithoutQueryString()
|
||||
{
|
||||
// Arrange
|
||||
GetAllUsersConsumptionStatisticsRequest request = _getAllUsersConsumptionStatisticsRequestFixture.Create(
|
||||
includeLibraryId: false,
|
||||
includeMediaKind: false,
|
||||
includeFromUtc: false,
|
||||
includeToUtc: false);
|
||||
_mockApiHttpClient.GetAsync<AllUsersConsumptionStatisticsDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_allUsersConsumptionStatisticsDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<AllUsersConsumptionStatisticsDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == ApiRoutes.LibraryStatistics.GET_ALL_USERS_CONSUMPTION_STATISTICS),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenAllFiltersAreSupplied_ShouldAppendEveryFilterToTheUpstreamQuery()
|
||||
{
|
||||
// Arrange
|
||||
GetAllUsersConsumptionStatisticsRequest request = _getAllUsersConsumptionStatisticsRequestFixture.Create(
|
||||
libraryId: "lib-1",
|
||||
mediaKind: MediaKind.Movie,
|
||||
fromUtc: s_fromUtc,
|
||||
toUtc: s_toUtc);
|
||||
_mockApiHttpClient.GetAsync<AllUsersConsumptionStatisticsDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_allUsersConsumptionStatisticsDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<AllUsersConsumptionStatisticsDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/consumption-statistics?libraryId=lib-1&mediaKind=Movie&fromUtc=2024-03-04T05%3A06%3A07.0000000Z&toUtc=2025-06-07T08%3A09%3A10.0000000Z"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOnlyLibraryIdIsSupplied_ShouldOmitEveryOtherFilter()
|
||||
{
|
||||
// Arrange
|
||||
GetAllUsersConsumptionStatisticsRequest request = _getAllUsersConsumptionStatisticsRequestFixture.Create(
|
||||
libraryId: "lib-1",
|
||||
includeMediaKind: false,
|
||||
includeFromUtc: false,
|
||||
includeToUtc: false);
|
||||
_mockApiHttpClient.GetAsync<AllUsersConsumptionStatisticsDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_allUsersConsumptionStatisticsDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<AllUsersConsumptionStatisticsDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/consumption-statistics?libraryId=lib-1"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOnlyMediaKindIsSupplied_ShouldOmitEveryOtherFilter()
|
||||
{
|
||||
// Arrange
|
||||
GetAllUsersConsumptionStatisticsRequest request = _getAllUsersConsumptionStatisticsRequestFixture.Create(
|
||||
mediaKind: MediaKind.Book,
|
||||
includeLibraryId: false,
|
||||
includeFromUtc: false,
|
||||
includeToUtc: false);
|
||||
_mockApiHttpClient.GetAsync<AllUsersConsumptionStatisticsDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_allUsersConsumptionStatisticsDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<AllUsersConsumptionStatisticsDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/consumption-statistics?mediaKind=Book"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOnlyFromUtcIsSupplied_ShouldOmitEveryOtherFilter()
|
||||
{
|
||||
// Arrange
|
||||
GetAllUsersConsumptionStatisticsRequest request = _getAllUsersConsumptionStatisticsRequestFixture.Create(
|
||||
fromUtc: s_fromUtc,
|
||||
includeLibraryId: false,
|
||||
includeMediaKind: false,
|
||||
includeToUtc: false);
|
||||
_mockApiHttpClient.GetAsync<AllUsersConsumptionStatisticsDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_allUsersConsumptionStatisticsDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<AllUsersConsumptionStatisticsDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/consumption-statistics?fromUtc=2024-03-04T05%3A06%3A07.0000000Z"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOnlyToUtcIsSupplied_ShouldOmitEveryOtherFilter()
|
||||
{
|
||||
// Arrange
|
||||
GetAllUsersConsumptionStatisticsRequest request = _getAllUsersConsumptionStatisticsRequestFixture.Create(
|
||||
toUtc: s_toUtc,
|
||||
includeLibraryId: false,
|
||||
includeMediaKind: false,
|
||||
includeFromUtc: false);
|
||||
_mockApiHttpClient.GetAsync<AllUsersConsumptionStatisticsDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_allUsersConsumptionStatisticsDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<AllUsersConsumptionStatisticsDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/consumption-statistics?toUtc=2025-06-07T08%3A09%3A10.0000000Z"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenLibraryIdContainsUrlSyntax_ShouldEscapeItInTheUpstreamQuery()
|
||||
{
|
||||
// Arrange
|
||||
GetAllUsersConsumptionStatisticsRequest request = _getAllUsersConsumptionStatisticsRequestFixture.Create(
|
||||
libraryId: "lib?x=1&y=2",
|
||||
includeMediaKind: false,
|
||||
includeFromUtc: false,
|
||||
includeToUtc: false);
|
||||
_mockApiHttpClient.GetAsync<AllUsersConsumptionStatisticsDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_allUsersConsumptionStatisticsDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<AllUsersConsumptionStatisticsDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/consumption-statistics?libraryId=lib%3Fx%3D1%26y%3D2"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSetPrivateNoStoreAndCookieVaryHeaders()
|
||||
{
|
||||
// Arrange
|
||||
GetAllUsersConsumptionStatisticsRequest request = _getAllUsersConsumptionStatisticsRequestFixture.Create();
|
||||
_mockApiHttpClient.GetAsync<AllUsersConsumptionStatisticsDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_allUsersConsumptionStatisticsDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, 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 void Configure_WhenCalled_ShouldRestrictTheRouteToAdministrators()
|
||||
{
|
||||
// Act
|
||||
_sut.Configure();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(_sut.Definition.PreBuiltUserPolicies);
|
||||
Assert.Contains(AuthorizationPolicies.REQUIRE_ADMIN_ROLE, _sut.Definition.PreBuiltUserPolicies);
|
||||
Assert.Contains("GET", _sut.Definition.Verbs);
|
||||
Assert.Contains(WebRoutes.LibraryStatistics.GET_ALL_USERS_STATISTICS, _sut.Definition.Routes);
|
||||
}
|
||||
}
|
||||
+221
@@ -0,0 +1,221 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.MediaConsumption;
|
||||
using Lumina.Presentation.Web.Common.Enums.MediaConsumption;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.Statistics;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetConsumptionStatistics;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.MediaConsumption;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Statistics;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.Statistics.GetConsumptionStatistics;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetConsumptionStatisticsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetConsumptionStatisticsEndpointTests
|
||||
{
|
||||
private static readonly DateTime s_fromUtc = new(2024, 3, 4, 5, 6, 7, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_toUtc = new(2025, 6, 7, 8, 9, 10, DateTimeKind.Utc);
|
||||
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly GetConsumptionStatisticsEndpoint _sut;
|
||||
private readonly GetConsumptionStatisticsRequestFixture _getConsumptionStatisticsRequestFixture = new();
|
||||
private readonly ConsumptionSummaryDtoFixture _consumptionSummaryDtoFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetConsumptionStatisticsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetConsumptionStatisticsEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<GetConsumptionStatisticsEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsStatistics_ShouldReturnSuccessJsonWithStatistics()
|
||||
{
|
||||
// Arrange
|
||||
ConsumptionSummaryDto expectedStatistics = _consumptionSummaryDtoFixture.Create();
|
||||
_mockApiHttpClient.GetAsync<ConsumptionSummaryDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedStatistics);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(
|
||||
_getConsumptionStatisticsRequestFixture.Create(includeUserId: false, includeLibraryId: false, includeMediaKind: false, includeFromUtc: false, includeToUtc: false),
|
||||
CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
ConsumptionSummaryDto? returnedStatistics = jsonDocument.RootElement.GetProperty("data").Deserialize<ConsumptionSummaryDto>(_jsonOptions);
|
||||
Assert.NotNull(returnedStatistics);
|
||||
Assert.Equal(expectedStatistics.UserId, returnedStatistics.UserId);
|
||||
Assert.Equal(expectedStatistics.CountedSessionCount, returnedStatistics.CountedSessionCount);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // No user selected, the current user is implied.
|
||||
[InlineData("")] // Empty user selected.
|
||||
[InlineData(" ")] // Whitespace user selected.
|
||||
public async Task ExecuteAsync_WhenUserIdIsNullOrWhitespace_ShouldRequestCurrentUserStatisticsWithoutQueryString(string? userId)
|
||||
{
|
||||
// Arrange
|
||||
GetConsumptionStatisticsRequest request = _getConsumptionStatisticsRequestFixture.Create(
|
||||
userId: userId,
|
||||
includeUserId: userId is not null,
|
||||
includeLibraryId: false,
|
||||
includeMediaKind: false,
|
||||
includeFromUtc: false,
|
||||
includeToUtc: false);
|
||||
_mockApiHttpClient.GetAsync<ConsumptionSummaryDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_consumptionSummaryDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<ConsumptionSummaryDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == ApiRoutes.LibraryStatistics.GET_CONSUMPTION_STATISTICS),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenUserIdAndAllFiltersAreSupplied_ShouldRequestUserStatisticsWithEscapedValues()
|
||||
{
|
||||
// Arrange
|
||||
GetConsumptionStatisticsRequest request = _getConsumptionStatisticsRequestFixture.Create(
|
||||
userId: "user/../admin?x=1&y=2",
|
||||
libraryId: "lib?x=1&y=2",
|
||||
mediaKind: MediaKind.Movie,
|
||||
fromUtc: s_fromUtc,
|
||||
toUtc: s_toUtc);
|
||||
_mockApiHttpClient.GetAsync<ConsumptionSummaryDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_consumptionSummaryDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<ConsumptionSummaryDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/user%2F..%2Fadmin%3Fx%3D1%26y%3D2/consumption-statistics?libraryId=lib%3Fx%3D1%26y%3D2&mediaKind=Movie&fromUtc=2024-03-04T05%3A06%3A07.0000000Z&toUtc=2025-06-07T08%3A09%3A10.0000000Z"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOnlyLibraryIdIsSupplied_ShouldOmitEveryOtherFilter()
|
||||
{
|
||||
// Arrange
|
||||
GetConsumptionStatisticsRequest request = _getConsumptionStatisticsRequestFixture.Create(
|
||||
libraryId: "lib-1",
|
||||
includeUserId: false,
|
||||
includeMediaKind: false,
|
||||
includeFromUtc: false,
|
||||
includeToUtc: false);
|
||||
_mockApiHttpClient.GetAsync<ConsumptionSummaryDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_consumptionSummaryDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<ConsumptionSummaryDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/me/consumption-statistics?libraryId=lib-1"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOnlyMediaKindIsSupplied_ShouldOmitEveryOtherFilter()
|
||||
{
|
||||
// Arrange
|
||||
GetConsumptionStatisticsRequest request = _getConsumptionStatisticsRequestFixture.Create(
|
||||
mediaKind: MediaKind.Book,
|
||||
includeUserId: false,
|
||||
includeLibraryId: false,
|
||||
includeFromUtc: false,
|
||||
includeToUtc: false);
|
||||
_mockApiHttpClient.GetAsync<ConsumptionSummaryDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_consumptionSummaryDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<ConsumptionSummaryDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/me/consumption-statistics?mediaKind=Book"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOnlyFromUtcIsSupplied_ShouldOmitEveryOtherFilter()
|
||||
{
|
||||
// Arrange
|
||||
GetConsumptionStatisticsRequest request = _getConsumptionStatisticsRequestFixture.Create(
|
||||
fromUtc: s_fromUtc,
|
||||
includeUserId: false,
|
||||
includeLibraryId: false,
|
||||
includeMediaKind: false,
|
||||
includeToUtc: false);
|
||||
_mockApiHttpClient.GetAsync<ConsumptionSummaryDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_consumptionSummaryDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<ConsumptionSummaryDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/me/consumption-statistics?fromUtc=2024-03-04T05%3A06%3A07.0000000Z"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOnlyToUtcIsSupplied_ShouldOmitEveryOtherFilter()
|
||||
{
|
||||
// Arrange
|
||||
GetConsumptionStatisticsRequest request = _getConsumptionStatisticsRequestFixture.Create(
|
||||
toUtc: s_toUtc,
|
||||
includeUserId: false,
|
||||
includeLibraryId: false,
|
||||
includeMediaKind: false,
|
||||
includeFromUtc: false);
|
||||
_mockApiHttpClient.GetAsync<ConsumptionSummaryDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_consumptionSummaryDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<ConsumptionSummaryDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/me/consumption-statistics?toUtc=2025-06-07T08%3A09%3A10.0000000Z"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSetPrivateNoStoreAndCookieVaryHeaders()
|
||||
{
|
||||
// Arrange
|
||||
GetConsumptionStatisticsRequest request = _getConsumptionStatisticsRequestFixture.Create();
|
||||
_mockApiHttpClient.GetAsync<ConsumptionSummaryDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_consumptionSummaryDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString());
|
||||
Assert.Equal("Cookie", _sut.HttpContext.Response.Headers["Vary"].ToString());
|
||||
}
|
||||
}
|
||||
+222
@@ -0,0 +1,222 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.MediaConsumption;
|
||||
using Lumina.Presentation.Web.Common.Enums.MediaConsumption;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.Statistics;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetGenreConsumption;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.MediaConsumption;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Statistics;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
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.Library.Statistics.GetGenreConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetGenreConsumptionEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetGenreConsumptionEndpointTests
|
||||
{
|
||||
private static readonly DateTime s_fromUtc = new(2024, 3, 4, 5, 6, 7, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_toUtc = new(2025, 6, 7, 8, 9, 10, DateTimeKind.Utc);
|
||||
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly GetGenreConsumptionEndpoint _sut;
|
||||
private readonly GetGenreConsumptionRequestFixture _getGenreConsumptionRequestFixture = new();
|
||||
private readonly GenreConsumptionDtoFixture _genreConsumptionDtoFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetGenreConsumptionEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetGenreConsumptionEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<GetGenreConsumptionEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsGenres_ShouldReturnSuccessJsonWithGenres()
|
||||
{
|
||||
// Arrange
|
||||
GenreConsumptionDto[] expectedGenres = [.. _genreConsumptionDtoFixture.CreateMany(2)];
|
||||
_mockApiHttpClient.GetAsync<GenreConsumptionDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedGenres);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(
|
||||
_getGenreConsumptionRequestFixture.Create(includeUserId: false, includeLibraryId: false, includeMediaKind: false, includeFromUtc: false, includeToUtc: false),
|
||||
CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
GenreConsumptionDto[]? returnedGenres = jsonDocument.RootElement.GetProperty("data").Deserialize<GenreConsumptionDto[]>(_jsonOptions);
|
||||
Assert.NotNull(returnedGenres);
|
||||
Assert.Equal(expectedGenres.Select(genre => genre.Name), returnedGenres.Select(genre => genre.Name));
|
||||
Assert.Equal(expectedGenres.Select(genre => genre.ConsumedItemCount), returnedGenres.Select(genre => genre.ConsumedItemCount));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // No user selected, the current user is implied.
|
||||
[InlineData("")] // Empty user selected.
|
||||
[InlineData(" ")] // Whitespace user selected.
|
||||
public async Task ExecuteAsync_WhenUserIdIsNullOrWhitespace_ShouldRequestCurrentUserGenresWithoutQueryString(string? userId)
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionRequest request = _getGenreConsumptionRequestFixture.Create(
|
||||
userId: userId,
|
||||
includeUserId: userId is not null,
|
||||
includeLibraryId: false,
|
||||
includeMediaKind: false,
|
||||
includeFromUtc: false,
|
||||
includeToUtc: false);
|
||||
_mockApiHttpClient.GetAsync<GenreConsumptionDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns([.. _genreConsumptionDtoFixture.CreateMany(1)]);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<GenreConsumptionDto[]>(
|
||||
Arg.Is<string>(endpoint => endpoint == ApiRoutes.LibraryStatistics.GET_GENRE_CONSUMPTION),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenUserIdAndAllFiltersAreSupplied_ShouldRequestUserGenresWithEscapedValues()
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionRequest request = _getGenreConsumptionRequestFixture.Create(
|
||||
userId: "user/../admin?x=1&y=2",
|
||||
libraryId: "lib?x=1&y=2",
|
||||
mediaKind: MediaKind.Movie,
|
||||
fromUtc: s_fromUtc,
|
||||
toUtc: s_toUtc);
|
||||
_mockApiHttpClient.GetAsync<GenreConsumptionDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns([.. _genreConsumptionDtoFixture.CreateMany(1)]);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<GenreConsumptionDto[]>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/user%2F..%2Fadmin%3Fx%3D1%26y%3D2/consumption-statistics/genres?libraryId=lib%3Fx%3D1%26y%3D2&mediaKind=Movie&fromUtc=2024-03-04T05%3A06%3A07.0000000Z&toUtc=2025-06-07T08%3A09%3A10.0000000Z"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOnlyLibraryIdIsSupplied_ShouldOmitEveryOtherFilter()
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionRequest request = _getGenreConsumptionRequestFixture.Create(
|
||||
libraryId: "lib-1",
|
||||
includeUserId: false,
|
||||
includeMediaKind: false,
|
||||
includeFromUtc: false,
|
||||
includeToUtc: false);
|
||||
_mockApiHttpClient.GetAsync<GenreConsumptionDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns([.. _genreConsumptionDtoFixture.CreateMany(1)]);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<GenreConsumptionDto[]>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/me/consumption-statistics/genres?libraryId=lib-1"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOnlyMediaKindIsSupplied_ShouldOmitEveryOtherFilter()
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionRequest request = _getGenreConsumptionRequestFixture.Create(
|
||||
mediaKind: MediaKind.Book,
|
||||
includeUserId: false,
|
||||
includeLibraryId: false,
|
||||
includeFromUtc: false,
|
||||
includeToUtc: false);
|
||||
_mockApiHttpClient.GetAsync<GenreConsumptionDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns([.. _genreConsumptionDtoFixture.CreateMany(1)]);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<GenreConsumptionDto[]>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/me/consumption-statistics/genres?mediaKind=Book"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOnlyFromUtcIsSupplied_ShouldOmitEveryOtherFilter()
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionRequest request = _getGenreConsumptionRequestFixture.Create(
|
||||
fromUtc: s_fromUtc,
|
||||
includeUserId: false,
|
||||
includeLibraryId: false,
|
||||
includeMediaKind: false,
|
||||
includeToUtc: false);
|
||||
_mockApiHttpClient.GetAsync<GenreConsumptionDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns([.. _genreConsumptionDtoFixture.CreateMany(1)]);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<GenreConsumptionDto[]>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/me/consumption-statistics/genres?fromUtc=2024-03-04T05%3A06%3A07.0000000Z"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOnlyToUtcIsSupplied_ShouldOmitEveryOtherFilter()
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionRequest request = _getGenreConsumptionRequestFixture.Create(
|
||||
toUtc: s_toUtc,
|
||||
includeUserId: false,
|
||||
includeLibraryId: false,
|
||||
includeMediaKind: false,
|
||||
includeFromUtc: false);
|
||||
_mockApiHttpClient.GetAsync<GenreConsumptionDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns([.. _genreConsumptionDtoFixture.CreateMany(1)]);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<GenreConsumptionDto[]>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/me/consumption-statistics/genres?toUtc=2025-06-07T08%3A09%3A10.0000000Z"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSetPrivateNoStoreAndCookieVaryHeaders()
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionRequest request = _getGenreConsumptionRequestFixture.Create();
|
||||
_mockApiHttpClient.GetAsync<GenreConsumptionDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns([.. _genreConsumptionDtoFixture.CreateMany(1)]);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString());
|
||||
Assert.Equal("Cookie", _sut.HttpContext.Response.Headers["Vary"].ToString());
|
||||
}
|
||||
}
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetLibraries;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
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.Library.Statistics.GetLibraries;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetLibrariesEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetLibrariesEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly GetLibrariesEndpoint _sut;
|
||||
private readonly LibraryDtoFixture _libraryDtoFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetLibrariesEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetLibrariesEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<GetLibrariesEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsLibraries_ShouldReturnSuccessJsonWithLibraries()
|
||||
{
|
||||
// Arrange
|
||||
LibraryDto[] expectedLibraries = [.. _libraryDtoFixture.CreateMany(2)];
|
||||
_mockApiHttpClient.GetAsync<LibraryDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedLibraries);
|
||||
|
||||
// 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());
|
||||
LibraryDto[]? returnedLibraries = jsonDocument.RootElement.GetProperty("data").Deserialize<LibraryDto[]>(_jsonOptions);
|
||||
Assert.NotNull(returnedLibraries);
|
||||
Assert.Equal(expectedLibraries.Select(library => library.Id), returnedLibraries.Select(library => library.Id));
|
||||
Assert.Equal(expectedLibraries.Select(library => library.Title), returnedLibraries.Select(library => library.Title));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldRequestEnabledLibrariesFromApi()
|
||||
{
|
||||
// Arrange
|
||||
_mockApiHttpClient.GetAsync<LibraryDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns([.. _libraryDtoFixture.CreateMany(2)]);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<LibraryDto[]>(
|
||||
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Libraries.GET_ENABLED_LIBRARIES),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSetPrivateNoStoreAndCookieVaryHeaders()
|
||||
{
|
||||
// Arrange
|
||||
_mockApiHttpClient.GetAsync<LibraryDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns([.. _libraryDtoFixture.CreateMany(1)]);
|
||||
|
||||
// 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());
|
||||
}
|
||||
}
|
||||
+197
@@ -0,0 +1,197 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Common.DTO.MediaConsumption;
|
||||
using Lumina.Presentation.Web.Common.Enums.MediaConsumption;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.Statistics;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetMostConsumed;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.MediaConsumption;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Statistics;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
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.Library.Statistics.GetMostConsumed;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetMostConsumedEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetMostConsumedEndpointTests
|
||||
{
|
||||
private static readonly DateTime s_fromUtc = new(2024, 3, 4, 5, 6, 7, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_toUtc = new(2025, 6, 7, 8, 9, 10, DateTimeKind.Utc);
|
||||
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly GetMostConsumedEndpoint _sut;
|
||||
private readonly GetMostConsumedRequestFixture _getMostConsumedRequestFixture = new();
|
||||
private readonly ConsumedItemDtoFixture _consumedItemDtoFixture = new();
|
||||
private readonly PaginatedDtoFixture<ConsumedItemDto> _paginatedDtoFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetMostConsumedEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetMostConsumedEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<GetMostConsumedEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsMostConsumedItems_ShouldReturnSuccessJsonWithPage()
|
||||
{
|
||||
// Arrange
|
||||
PaginatedDto<ConsumedItemDto> expectedPage = _paginatedDtoFixture.Create(
|
||||
data: [.. _consumedItemDtoFixture.CreateMany(2)],
|
||||
currentPage: 2,
|
||||
perPage: 5,
|
||||
count: 12,
|
||||
numberOfPages: 3);
|
||||
_mockApiHttpClient.GetAsync<PaginatedDto<ConsumedItemDto>>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedPage);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(
|
||||
_getMostConsumedRequestFixture.Create(includeUserId: false, includeLibraryId: false, includeMediaKind: false, includeFromUtc: false, includeToUtc: false),
|
||||
CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
PaginatedDto<ConsumedItemDto>? returnedPage = jsonDocument.RootElement.GetProperty("data").Deserialize<PaginatedDto<ConsumedItemDto>>(_jsonOptions);
|
||||
Assert.NotNull(returnedPage);
|
||||
Assert.Equal(expectedPage.Count, returnedPage.Count);
|
||||
Assert.Equal(expectedPage.CurrentPage, returnedPage.CurrentPage);
|
||||
Assert.Equal(expectedPage.PerPage, returnedPage.PerPage);
|
||||
Assert.Equal(expectedPage.NumberOfPages, returnedPage.NumberOfPages);
|
||||
Assert.Equal(expectedPage.Data.Select(item => item.MediaItemId), returnedPage.Data.Select(item => item.MediaItemId));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // No user selected, the current user is implied.
|
||||
[InlineData("")] // Empty user selected.
|
||||
[InlineData(" ")] // Whitespace user selected.
|
||||
public async Task ExecuteAsync_WhenUserIdIsNullOrWhitespaceAndNoFilterIsSupplied_ShouldRequestCurrentUserItemsWithDefaultPaging(string? userId)
|
||||
{
|
||||
// Arrange
|
||||
GetMostConsumedRequest request = _getMostConsumedRequestFixture.Create(
|
||||
userId: userId,
|
||||
includeUserId: userId is not null,
|
||||
includeLibraryId: false,
|
||||
includeMediaKind: false,
|
||||
includeFromUtc: false,
|
||||
includeToUtc: false,
|
||||
includeCurrentPage: false,
|
||||
includePerPage: false);
|
||||
_mockApiHttpClient.GetAsync<PaginatedDto<ConsumedItemDto>>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedDtoFixture.Create(data: []));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedDto<ConsumedItemDto>>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/me/consumption-history/most-consumed?currentPage=1&perPage=10"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOnlyPagingIsSupplied_ShouldOmitEveryOptionalFilter()
|
||||
{
|
||||
// Arrange
|
||||
GetMostConsumedRequest request = _getMostConsumedRequestFixture.Create(
|
||||
currentPage: 3,
|
||||
perPage: 25,
|
||||
includeUserId: false,
|
||||
includeLibraryId: false,
|
||||
includeMediaKind: false,
|
||||
includeFromUtc: false,
|
||||
includeToUtc: false);
|
||||
_mockApiHttpClient.GetAsync<PaginatedDto<ConsumedItemDto>>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedDtoFixture.Create(data: []));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedDto<ConsumedItemDto>>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/me/consumption-history/most-consumed?currentPage=3&perPage=25"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOnlyLibraryIdIsSupplied_ShouldOmitEveryOtherFilterAndUseDefaultPaging()
|
||||
{
|
||||
// Arrange
|
||||
GetMostConsumedRequest request = _getMostConsumedRequestFixture.Create(
|
||||
libraryId: "lib-1",
|
||||
includeUserId: false,
|
||||
includeMediaKind: false,
|
||||
includeFromUtc: false,
|
||||
includeToUtc: false,
|
||||
includeCurrentPage: false,
|
||||
includePerPage: false);
|
||||
_mockApiHttpClient.GetAsync<PaginatedDto<ConsumedItemDto>>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedDtoFixture.Create(data: []));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedDto<ConsumedItemDto>>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/me/consumption-history/most-consumed?libraryId=lib-1¤tPage=1&perPage=10"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenUserIdAndAllFiltersAreSupplied_ShouldRequestUserItemsWithEscapedValues()
|
||||
{
|
||||
// Arrange
|
||||
GetMostConsumedRequest request = _getMostConsumedRequestFixture.Create(
|
||||
userId: "user/../admin?x=1&y=2",
|
||||
libraryId: "lib?x=1&y=2",
|
||||
mediaKind: MediaKind.Movie,
|
||||
fromUtc: s_fromUtc,
|
||||
toUtc: s_toUtc,
|
||||
currentPage: 4,
|
||||
perPage: 20);
|
||||
_mockApiHttpClient.GetAsync<PaginatedDto<ConsumedItemDto>>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedDtoFixture.Create(data: []));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedDto<ConsumedItemDto>>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/user%2F..%2Fadmin%3Fx%3D1%26y%3D2/consumption-history/most-consumed?libraryId=lib%3Fx%3D1%26y%3D2&mediaKind=Movie&fromUtc=2024-03-04T05%3A06%3A07.0000000Z&toUtc=2025-06-07T08%3A09%3A10.0000000Z¤tPage=4&perPage=20"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSetPrivateNoStoreAndCookieVaryHeaders()
|
||||
{
|
||||
// Arrange
|
||||
GetMostConsumedRequest request = _getMostConsumedRequestFixture.Create();
|
||||
_mockApiHttpClient.GetAsync<PaginatedDto<ConsumedItemDto>>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedDtoFixture.Create(data: []));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString());
|
||||
Assert.Equal("Cookie", _sut.HttpContext.Response.Headers["Vary"].ToString());
|
||||
}
|
||||
}
|
||||
+197
@@ -0,0 +1,197 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Common.DTO.MediaConsumption;
|
||||
using Lumina.Presentation.Web.Common.Enums.MediaConsumption;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.Statistics;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetRecentlyConsumed;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.MediaConsumption;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Statistics;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
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.Library.Statistics.GetRecentlyConsumed;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetRecentlyConsumedEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetRecentlyConsumedEndpointTests
|
||||
{
|
||||
private static readonly DateTime s_fromUtc = new(2024, 3, 4, 5, 6, 7, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_toUtc = new(2025, 6, 7, 8, 9, 10, DateTimeKind.Utc);
|
||||
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly GetRecentlyConsumedEndpoint _sut;
|
||||
private readonly GetRecentlyConsumedRequestFixture _getRecentlyConsumedRequestFixture = new();
|
||||
private readonly ConsumedItemDtoFixture _consumedItemDtoFixture = new();
|
||||
private readonly PaginatedDtoFixture<ConsumedItemDto> _paginatedDtoFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetRecentlyConsumedEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetRecentlyConsumedEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<GetRecentlyConsumedEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsRecentlyConsumedItems_ShouldReturnSuccessJsonWithPage()
|
||||
{
|
||||
// Arrange
|
||||
PaginatedDto<ConsumedItemDto> expectedPage = _paginatedDtoFixture.Create(
|
||||
data: [.. _consumedItemDtoFixture.CreateMany(2)],
|
||||
currentPage: 2,
|
||||
perPage: 5,
|
||||
count: 12,
|
||||
numberOfPages: 3);
|
||||
_mockApiHttpClient.GetAsync<PaginatedDto<ConsumedItemDto>>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedPage);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(
|
||||
_getRecentlyConsumedRequestFixture.Create(includeUserId: false, includeLibraryId: false, includeMediaKind: false, includeFromUtc: false, includeToUtc: false),
|
||||
CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
PaginatedDto<ConsumedItemDto>? returnedPage = jsonDocument.RootElement.GetProperty("data").Deserialize<PaginatedDto<ConsumedItemDto>>(_jsonOptions);
|
||||
Assert.NotNull(returnedPage);
|
||||
Assert.Equal(expectedPage.Count, returnedPage.Count);
|
||||
Assert.Equal(expectedPage.CurrentPage, returnedPage.CurrentPage);
|
||||
Assert.Equal(expectedPage.PerPage, returnedPage.PerPage);
|
||||
Assert.Equal(expectedPage.NumberOfPages, returnedPage.NumberOfPages);
|
||||
Assert.Equal(expectedPage.Data.Select(item => item.MediaItemId), returnedPage.Data.Select(item => item.MediaItemId));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // No user selected, the current user is implied.
|
||||
[InlineData("")] // Empty user selected.
|
||||
[InlineData(" ")] // Whitespace user selected.
|
||||
public async Task ExecuteAsync_WhenUserIdIsNullOrWhitespaceAndNoFilterIsSupplied_ShouldRequestCurrentUserItemsWithDefaultPaging(string? userId)
|
||||
{
|
||||
// Arrange
|
||||
GetRecentlyConsumedRequest request = _getRecentlyConsumedRequestFixture.Create(
|
||||
userId: userId,
|
||||
includeUserId: userId is not null,
|
||||
includeLibraryId: false,
|
||||
includeMediaKind: false,
|
||||
includeFromUtc: false,
|
||||
includeToUtc: false,
|
||||
includeCurrentPage: false,
|
||||
includePerPage: false);
|
||||
_mockApiHttpClient.GetAsync<PaginatedDto<ConsumedItemDto>>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedDtoFixture.Create(data: []));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedDto<ConsumedItemDto>>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/me/consumption-history/recently-consumed?currentPage=1&perPage=10"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOnlyPagingIsSupplied_ShouldOmitEveryOptionalFilter()
|
||||
{
|
||||
// Arrange
|
||||
GetRecentlyConsumedRequest request = _getRecentlyConsumedRequestFixture.Create(
|
||||
currentPage: 3,
|
||||
perPage: 25,
|
||||
includeUserId: false,
|
||||
includeLibraryId: false,
|
||||
includeMediaKind: false,
|
||||
includeFromUtc: false,
|
||||
includeToUtc: false);
|
||||
_mockApiHttpClient.GetAsync<PaginatedDto<ConsumedItemDto>>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedDtoFixture.Create(data: []));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedDto<ConsumedItemDto>>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/me/consumption-history/recently-consumed?currentPage=3&perPage=25"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOnlyLibraryIdIsSupplied_ShouldOmitEveryOtherFilterAndUseDefaultPaging()
|
||||
{
|
||||
// Arrange
|
||||
GetRecentlyConsumedRequest request = _getRecentlyConsumedRequestFixture.Create(
|
||||
libraryId: "lib-1",
|
||||
includeUserId: false,
|
||||
includeMediaKind: false,
|
||||
includeFromUtc: false,
|
||||
includeToUtc: false,
|
||||
includeCurrentPage: false,
|
||||
includePerPage: false);
|
||||
_mockApiHttpClient.GetAsync<PaginatedDto<ConsumedItemDto>>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedDtoFixture.Create(data: []));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedDto<ConsumedItemDto>>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/me/consumption-history/recently-consumed?libraryId=lib-1¤tPage=1&perPage=10"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenUserIdAndAllFiltersAreSupplied_ShouldRequestUserItemsWithEscapedValues()
|
||||
{
|
||||
// Arrange
|
||||
GetRecentlyConsumedRequest request = _getRecentlyConsumedRequestFixture.Create(
|
||||
userId: "user/../admin?x=1&y=2",
|
||||
libraryId: "lib?x=1&y=2",
|
||||
mediaKind: MediaKind.Movie,
|
||||
fromUtc: s_fromUtc,
|
||||
toUtc: s_toUtc,
|
||||
currentPage: 4,
|
||||
perPage: 20);
|
||||
_mockApiHttpClient.GetAsync<PaginatedDto<ConsumedItemDto>>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedDtoFixture.Create(data: []));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedDto<ConsumedItemDto>>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/user%2F..%2Fadmin%3Fx%3D1%26y%3D2/consumption-history/recently-consumed?libraryId=lib%3Fx%3D1%26y%3D2&mediaKind=Movie&fromUtc=2024-03-04T05%3A06%3A07.0000000Z&toUtc=2025-06-07T08%3A09%3A10.0000000Z¤tPage=4&perPage=20"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSetPrivateNoStoreAndCookieVaryHeaders()
|
||||
{
|
||||
// Arrange
|
||||
GetRecentlyConsumedRequest request = _getRecentlyConsumedRequestFixture.Create();
|
||||
_mockApiHttpClient.GetAsync<PaginatedDto<ConsumedItemDto>>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedDtoFixture.Create(data: []));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString());
|
||||
Assert.Equal("Cookie", _sut.HttpContext.Response.Headers["Vary"].ToString());
|
||||
}
|
||||
}
|
||||
+222
@@ -0,0 +1,222 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.MediaConsumption;
|
||||
using Lumina.Presentation.Web.Common.Enums.MediaConsumption;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.Statistics;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetTagConsumption;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.MediaConsumption;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Statistics;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
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.Library.Statistics.GetTagConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetTagConsumptionEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetTagConsumptionEndpointTests
|
||||
{
|
||||
private static readonly DateTime s_fromUtc = new(2024, 3, 4, 5, 6, 7, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_toUtc = new(2025, 6, 7, 8, 9, 10, DateTimeKind.Utc);
|
||||
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly GetTagConsumptionEndpoint _sut;
|
||||
private readonly GetTagConsumptionRequestFixture _getTagConsumptionRequestFixture = new();
|
||||
private readonly TagConsumptionDtoFixture _tagConsumptionDtoFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetTagConsumptionEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetTagConsumptionEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<GetTagConsumptionEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsTags_ShouldReturnSuccessJsonWithTags()
|
||||
{
|
||||
// Arrange
|
||||
TagConsumptionDto[] expectedTags = [.. _tagConsumptionDtoFixture.CreateMany(2)];
|
||||
_mockApiHttpClient.GetAsync<TagConsumptionDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedTags);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(
|
||||
_getTagConsumptionRequestFixture.Create(includeUserId: false, includeLibraryId: false, includeMediaKind: false, includeFromUtc: false, includeToUtc: false),
|
||||
CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
TagConsumptionDto[]? returnedTags = jsonDocument.RootElement.GetProperty("data").Deserialize<TagConsumptionDto[]>(_jsonOptions);
|
||||
Assert.NotNull(returnedTags);
|
||||
Assert.Equal(expectedTags.Select(tag => tag.Name), returnedTags.Select(tag => tag.Name));
|
||||
Assert.Equal(expectedTags.Select(tag => tag.ConsumedItemCount), returnedTags.Select(tag => tag.ConsumedItemCount));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // No user selected, the current user is implied.
|
||||
[InlineData("")] // Empty user selected.
|
||||
[InlineData(" ")] // Whitespace user selected.
|
||||
public async Task ExecuteAsync_WhenUserIdIsNullOrWhitespace_ShouldRequestCurrentUserTagsWithoutQueryString(string? userId)
|
||||
{
|
||||
// Arrange
|
||||
GetTagConsumptionRequest request = _getTagConsumptionRequestFixture.Create(
|
||||
userId: userId,
|
||||
includeUserId: userId is not null,
|
||||
includeLibraryId: false,
|
||||
includeMediaKind: false,
|
||||
includeFromUtc: false,
|
||||
includeToUtc: false);
|
||||
_mockApiHttpClient.GetAsync<TagConsumptionDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns([.. _tagConsumptionDtoFixture.CreateMany(1)]);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<TagConsumptionDto[]>(
|
||||
Arg.Is<string>(endpoint => endpoint == ApiRoutes.LibraryStatistics.GET_TAG_CONSUMPTION),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenUserIdAndAllFiltersAreSupplied_ShouldRequestUserTagsWithEscapedValues()
|
||||
{
|
||||
// Arrange
|
||||
GetTagConsumptionRequest request = _getTagConsumptionRequestFixture.Create(
|
||||
userId: "user/../admin?x=1&y=2",
|
||||
libraryId: "lib?x=1&y=2",
|
||||
mediaKind: MediaKind.Movie,
|
||||
fromUtc: s_fromUtc,
|
||||
toUtc: s_toUtc);
|
||||
_mockApiHttpClient.GetAsync<TagConsumptionDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns([.. _tagConsumptionDtoFixture.CreateMany(1)]);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<TagConsumptionDto[]>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/user%2F..%2Fadmin%3Fx%3D1%26y%3D2/consumption-statistics/tags?libraryId=lib%3Fx%3D1%26y%3D2&mediaKind=Movie&fromUtc=2024-03-04T05%3A06%3A07.0000000Z&toUtc=2025-06-07T08%3A09%3A10.0000000Z"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOnlyLibraryIdIsSupplied_ShouldOmitEveryOtherFilter()
|
||||
{
|
||||
// Arrange
|
||||
GetTagConsumptionRequest request = _getTagConsumptionRequestFixture.Create(
|
||||
libraryId: "lib-1",
|
||||
includeUserId: false,
|
||||
includeMediaKind: false,
|
||||
includeFromUtc: false,
|
||||
includeToUtc: false);
|
||||
_mockApiHttpClient.GetAsync<TagConsumptionDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns([.. _tagConsumptionDtoFixture.CreateMany(1)]);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<TagConsumptionDto[]>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/me/consumption-statistics/tags?libraryId=lib-1"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOnlyMediaKindIsSupplied_ShouldOmitEveryOtherFilter()
|
||||
{
|
||||
// Arrange
|
||||
GetTagConsumptionRequest request = _getTagConsumptionRequestFixture.Create(
|
||||
mediaKind: MediaKind.Book,
|
||||
includeUserId: false,
|
||||
includeLibraryId: false,
|
||||
includeFromUtc: false,
|
||||
includeToUtc: false);
|
||||
_mockApiHttpClient.GetAsync<TagConsumptionDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns([.. _tagConsumptionDtoFixture.CreateMany(1)]);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<TagConsumptionDto[]>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/me/consumption-statistics/tags?mediaKind=Book"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOnlyFromUtcIsSupplied_ShouldOmitEveryOtherFilter()
|
||||
{
|
||||
// Arrange
|
||||
GetTagConsumptionRequest request = _getTagConsumptionRequestFixture.Create(
|
||||
fromUtc: s_fromUtc,
|
||||
includeUserId: false,
|
||||
includeLibraryId: false,
|
||||
includeMediaKind: false,
|
||||
includeToUtc: false);
|
||||
_mockApiHttpClient.GetAsync<TagConsumptionDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns([.. _tagConsumptionDtoFixture.CreateMany(1)]);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<TagConsumptionDto[]>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/me/consumption-statistics/tags?fromUtc=2024-03-04T05%3A06%3A07.0000000Z"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOnlyToUtcIsSupplied_ShouldOmitEveryOtherFilter()
|
||||
{
|
||||
// Arrange
|
||||
GetTagConsumptionRequest request = _getTagConsumptionRequestFixture.Create(
|
||||
toUtc: s_toUtc,
|
||||
includeUserId: false,
|
||||
includeLibraryId: false,
|
||||
includeMediaKind: false,
|
||||
includeFromUtc: false);
|
||||
_mockApiHttpClient.GetAsync<TagConsumptionDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns([.. _tagConsumptionDtoFixture.CreateMany(1)]);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<TagConsumptionDto[]>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/me/consumption-statistics/tags?toUtc=2025-06-07T08%3A09%3A10.0000000Z"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSetPrivateNoStoreAndCookieVaryHeaders()
|
||||
{
|
||||
// Arrange
|
||||
GetTagConsumptionRequest request = _getTagConsumptionRequestFixture.Create();
|
||||
_mockApiHttpClient.GetAsync<TagConsumptionDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns([.. _tagConsumptionDtoFixture.CreateMany(1)]);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString());
|
||||
Assert.Equal("Cookie", _sut.HttpContext.Response.Headers["Vary"].ToString());
|
||||
}
|
||||
}
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.Authorization;
|
||||
using Lumina.Presentation.Web.Common.DTO.UsersManagement;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetUsers;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.UsersManagement;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
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.Library.Statistics.GetUsers;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetUsersEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetUsersEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly GetUsersEndpoint _sut;
|
||||
private readonly UserDtoFixture _userDtoFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetUsersEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetUsersEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<GetUsersEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsUsers_ShouldReturnSuccessJsonWithUsers()
|
||||
{
|
||||
// Arrange
|
||||
UserDto[] expectedUsers = [.. _userDtoFixture.CreateMany(2)];
|
||||
_mockApiHttpClient.GetAsync<UserDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedUsers);
|
||||
|
||||
// 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());
|
||||
UserDto[]? returnedUsers = jsonDocument.RootElement.GetProperty("data").Deserialize<UserDto[]>(_jsonOptions);
|
||||
Assert.NotNull(returnedUsers);
|
||||
Assert.Equal(expectedUsers.Select(user => user.Id), returnedUsers.Select(user => user.Id));
|
||||
Assert.Equal(expectedUsers.Select(user => user.Username), returnedUsers.Select(user => user.Username));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldRequestUsersFromApi()
|
||||
{
|
||||
// Arrange
|
||||
_mockApiHttpClient.GetAsync<UserDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns([.. _userDtoFixture.CreateMany(2)]);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<UserDto[]>(
|
||||
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Authentication.USERS),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSetPrivateNoStoreAndCookieVaryHeaders()
|
||||
{
|
||||
// Arrange
|
||||
_mockApiHttpClient.GetAsync<UserDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns([.. _userDtoFixture.CreateMany(1)]);
|
||||
|
||||
// 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 void Configure_WhenCalled_ShouldRestrictTheRouteToAdministrators()
|
||||
{
|
||||
// Act
|
||||
_sut.Configure();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(_sut.Definition.PreBuiltUserPolicies);
|
||||
Assert.Contains(AuthorizationPolicies.REQUIRE_ADMIN_ROLE, _sut.Definition.PreBuiltUserPolicies);
|
||||
Assert.Contains("GET", _sut.Definition.Verbs);
|
||||
Assert.Contains(WebRoutes.LibraryStatistics.GET_USERS, _sut.Definition.Routes);
|
||||
}
|
||||
}
|
||||
+335
@@ -0,0 +1,335 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.Authorization;
|
||||
using Lumina.Presentation.Web.Common.DTO.Themes;
|
||||
using Lumina.Presentation.Web.Common.Http;
|
||||
using Lumina.Presentation.Web.Common.Primitives;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Common.Services;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.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.Http;
|
||||
using Microsoft.Extensions.Localization;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Security.Claims;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.Statistics.Index;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="StatisticsIndexViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class StatisticsIndexViewEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly IUrlService _mockUrlService;
|
||||
private readonly ThemePageRenderer _mockThemePageRenderer;
|
||||
private readonly IStringLocalizerFactory _mockStringLocalizerFactory;
|
||||
private readonly IStringLocalizer _mockStringLocalizer;
|
||||
private readonly IAuthorizationService _mockAuthorizationService;
|
||||
private readonly StatisticsIndexViewEndpoint _sut;
|
||||
private readonly ThemePageRenderResultDtoFixture _themePageRenderResultDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="StatisticsIndexViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public StatisticsIndexViewEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_mockUrlService = Substitute.For<IUrlService>();
|
||||
_mockThemePageRenderer = Substitute.For<ThemePageRenderer>(new ThemeService(_mockApiHttpClient), new ThemeTemplateEngine());
|
||||
_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("Title", "localized-Title"),
|
||||
new LocalizedString("Loading", "localized-Loading")
|
||||
]);
|
||||
_mockStringLocalizerFactory = Substitute.For<IStringLocalizerFactory>();
|
||||
_mockStringLocalizerFactory.Create(Arg.Any<string>(), Arg.Any<string>()).Returns(_mockStringLocalizer);
|
||||
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
|
||||
_sut = Factory.Create<StatisticsIndexViewEndpoint>(_mockUrlService, _mockThemePageRenderer, _mockStringLocalizerFactory, _mockAuthorizationService);
|
||||
TestHttpContextFactory.ConfigureSession(_sut.HttpContext, TestHttpContextFactory.CreateSession());
|
||||
TestHttpContextFactory.ConfigureCulture(_sut.HttpContext, "en-US");
|
||||
_sut.HttpContext.Request.Path = "/en-us/library/statistics";
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenThemeRenderingSucceeds_ShouldReturnThemedRazorViewResult()
|
||||
{
|
||||
// Arrange
|
||||
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_themePageRenderResultDtoFixture.Create(content: "<section>content</section>", script: "<script>script</script>")));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.IsType<RazorViewResult>(result);
|
||||
await _mockThemePageRenderer.Received(1).RenderAsync(
|
||||
Arg.Any<ThemePageDto>(),
|
||||
Arg.Is<string?>(requestedThemeId => requestedThemeId == null),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenThemeRenderingSucceeds_ShouldPassLocalizedTitleAndPageDataToTheThemeRenderer()
|
||||
{
|
||||
// Arrange
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_STATISTICS).Returns("http://localhost/en-us/library/statistics/api-get-statistics");
|
||||
_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 =>
|
||||
page.PageKey == "library/statistics/index" &&
|
||||
page.Title == "localized-Title" &&
|
||||
page.PageData.ContainsKey("getStatisticsUrl") &&
|
||||
page.PageData.ContainsKey("getAllUsersStatisticsUrl") &&
|
||||
page.PageData.ContainsKey("getRecentlyConsumedUrl") &&
|
||||
page.PageData.ContainsKey("getMostConsumedUrl") &&
|
||||
page.PageData.ContainsKey("getTagConsumptionUrl") &&
|
||||
page.PageData.ContainsKey("getGenreConsumptionUrl") &&
|
||||
page.PageData.ContainsKey("getLibrariesUrl") &&
|
||||
page.PageData.ContainsKey("getUsersUrl") &&
|
||||
page.PageData.ContainsKey("deleteConsumptionItemHistoryUrl") &&
|
||||
page.PageData.ContainsKey("clearConsumptionHistoryUrl") &&
|
||||
page.PageData.ContainsKey("clearResumePointsUrl") &&
|
||||
page.PageData.ContainsKey("culture") &&
|
||||
page.PageData.ContainsKey("isAdmin") &&
|
||||
page.PageData.ContainsKey("currentUserId") &&
|
||||
page.PageData.ContainsKey("strings") &&
|
||||
string.Equals(
|
||||
page.PageData["getStatisticsUrl"] as string,
|
||||
"http://localhost/en-us/library/statistics/api-get-statistics",
|
||||
StringComparison.Ordinal)),
|
||||
Arg.Is<string?>(requestedThemeId => requestedThemeId == null),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenThemeRenderingFails_ShouldReturnRazorViewResult()
|
||||
{
|
||||
// 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.IsType<RazorViewResult>(result);
|
||||
await _mockThemePageRenderer.Received(1).RenderAsync(
|
||||
Arg.Any<ThemePageDto>(),
|
||||
Arg.Is<string?>(requestedThemeId => requestedThemeId == null),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenUserIsAdmin_ShouldExposeAdminFlagUsersUrlAndCurrentUserId()
|
||||
{
|
||||
// Arrange
|
||||
Guid expectedUserId = Guid.NewGuid();
|
||||
ConfigureCurrentUser(expectedUserId.ToString());
|
||||
_mockAuthorizationService.IsInRoleAsync("Admin", Arg.Any<CancellationToken>()).Returns(true);
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_USERS).Returns("http://localhost/en-us/library/statistics/api-get-users");
|
||||
_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 =>
|
||||
Equals(page.PageData["isAdmin"], true) &&
|
||||
string.Equals(
|
||||
page.PageData["getUsersUrl"] as string,
|
||||
"http://localhost/en-us/library/statistics/api-get-users",
|
||||
StringComparison.Ordinal) &&
|
||||
page.PageData["currentUserId"] != null &&
|
||||
(Guid)page.PageData["currentUserId"]! == expectedUserId),
|
||||
Arg.Any<string?>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenUserIsNotAdmin_ShouldHideUsersUrl()
|
||||
{
|
||||
// Arrange
|
||||
ConfigureCurrentUser(Guid.NewGuid().ToString());
|
||||
_mockAuthorizationService.IsInRoleAsync("Admin", Arg.Any<CancellationToken>()).Returns(false);
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_USERS).Returns("http://localhost/en-us/library/statistics/api-get-users");
|
||||
_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 =>
|
||||
Equals(page.PageData["isAdmin"], false) &&
|
||||
string.Equals(page.PageData["getUsersUrl"] as string, string.Empty, StringComparison.Ordinal)),
|
||||
Arg.Any<string?>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
_mockUrlService.DidNotReceive().GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_USERS);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // No identifier claim at all.
|
||||
[InlineData("")] // Empty identifier claim.
|
||||
[InlineData("not-a-guid")] // Identifier claim that is not a GUID.
|
||||
public async Task ExecuteAsync_WhenNameIdentifierIsMissingOrNotAGuid_ShouldLeaveCurrentUserIdNull(string? nameIdentifier)
|
||||
{
|
||||
// Arrange
|
||||
ConfigureCurrentUser(nameIdentifier);
|
||||
_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 => page.PageData["currentUserId"] == null),
|
||||
Arg.Any<string?>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenUrlServiceReturnsUrls_ShouldExposeEveryUrlFromTheRouteConstants()
|
||||
{
|
||||
// Arrange
|
||||
_mockAuthorizationService.IsInRoleAsync("Admin", Arg.Any<CancellationToken>()).Returns(true);
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_STATISTICS).Returns("https://lumina.test/statistics");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_ALL_USERS_STATISTICS).Returns("https://lumina.test/all-users-statistics");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_RECENTLY_CONSUMED).Returns("https://lumina.test/recently-consumed");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_MOST_CONSUMED).Returns("https://lumina.test/most-consumed");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_TAG_CONSUMPTION).Returns("https://lumina.test/tag-consumption");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_GENRE_CONSUMPTION).Returns("https://lumina.test/genre-consumption");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_LIBRARIES).Returns("https://lumina.test/libraries");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_USERS).Returns("https://lumina.test/users");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.DELETE_CONSUMPTION_ITEM_HISTORY).Returns("https://lumina.test/delete-consumption-item-history");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.CLEAR_CONSUMPTION_HISTORY).Returns("https://lumina.test/clear-consumption-history");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.CLEAR_RESUME_POINTS).Returns("https://lumina.test/clear-resume-points");
|
||||
_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["getStatisticsUrl"] as string, "https://lumina.test/statistics", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["getAllUsersStatisticsUrl"] as string, "https://lumina.test/all-users-statistics", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["getRecentlyConsumedUrl"] as string, "https://lumina.test/recently-consumed", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["getMostConsumedUrl"] as string, "https://lumina.test/most-consumed", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["getTagConsumptionUrl"] as string, "https://lumina.test/tag-consumption", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["getGenreConsumptionUrl"] as string, "https://lumina.test/genre-consumption", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["getLibrariesUrl"] as string, "https://lumina.test/libraries", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["getUsersUrl"] as string, "https://lumina.test/users", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["deleteConsumptionItemHistoryUrl"] as string, "https://lumina.test/delete-consumption-item-history", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["clearConsumptionHistoryUrl"] as string, "https://lumina.test/clear-consumption-history", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["clearResumePointsUrl"] as string, "https://lumina.test/clear-resume-points", StringComparison.Ordinal)),
|
||||
Arg.Any<string?>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
_mockUrlService.Received(1).GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_STATISTICS);
|
||||
_mockUrlService.Received(1).GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_ALL_USERS_STATISTICS);
|
||||
_mockUrlService.Received(1).GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_RECENTLY_CONSUMED);
|
||||
_mockUrlService.Received(1).GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_MOST_CONSUMED);
|
||||
_mockUrlService.Received(1).GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_TAG_CONSUMPTION);
|
||||
_mockUrlService.Received(1).GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_GENRE_CONSUMPTION);
|
||||
_mockUrlService.Received(1).GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_LIBRARIES);
|
||||
_mockUrlService.Received(1).GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_USERS);
|
||||
_mockUrlService.Received(1).GetAbsoluteUrl(WebRoutes.LibraryStatistics.DELETE_CONSUMPTION_ITEM_HISTORY);
|
||||
_mockUrlService.Received(1).GetAbsoluteUrl(WebRoutes.LibraryStatistics.CLEAR_CONSUMPTION_HISTORY);
|
||||
_mockUrlService.Received(1).GetAbsoluteUrl(WebRoutes.LibraryStatistics.CLEAR_RESUME_POINTS);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenUrlServiceReturnsNull_ShouldExposeEmptyStrings()
|
||||
{
|
||||
// Arrange
|
||||
_mockAuthorizationService.IsInRoleAsync("Admin", Arg.Any<CancellationToken>()).Returns(true);
|
||||
_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["getStatisticsUrl"] as string, string.Empty, StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["getAllUsersStatisticsUrl"] as string, string.Empty, StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["getRecentlyConsumedUrl"] as string, string.Empty, StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["getMostConsumedUrl"] as string, string.Empty, StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["getTagConsumptionUrl"] as string, string.Empty, StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["getGenreConsumptionUrl"] as string, string.Empty, StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["getLibrariesUrl"] as string, string.Empty, StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["getUsersUrl"] as string, string.Empty, StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["deleteConsumptionItemHistoryUrl"] as string, string.Empty, StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["clearConsumptionHistoryUrl"] as string, string.Empty, StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["clearResumePointsUrl"] as string, string.Empty, StringComparison.Ordinal)),
|
||||
Arg.Any<string?>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCultureRouteValueIsSet_ShouldExposeThatCulture()
|
||||
{
|
||||
// Arrange
|
||||
TestHttpContextFactory.ConfigureCulture(_sut.HttpContext, "fr-FR");
|
||||
_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["culture"] as string, "fr-FR", StringComparison.Ordinal)),
|
||||
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());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Assigns a claims principal to the HTTP context of the endpoint under test.
|
||||
/// </summary>
|
||||
/// <param name="nameIdentifier">The value of the name identifier claim, or <see langword="null"/> to omit the claim.</param>
|
||||
private void ConfigureCurrentUser(string? nameIdentifier)
|
||||
{
|
||||
List<Claim> claims = nameIdentifier is null ? [] : [new Claim(ClaimTypes.NameIdentifier, nameIdentifier)];
|
||||
_sut.HttpContext.User = new ClaimsPrincipal(new ClaimsIdentity(claims, "TestAuthentication"));
|
||||
}
|
||||
}
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeleteBook;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeleteBook;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="DeleteBookEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteBookEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly DeleteBookEndpoint _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteBookEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public DeleteBookEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<DeleteBookEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldDeleteBookViaApiAndReturnSuccessWithoutData()
|
||||
{
|
||||
// Arrange
|
||||
Guid bookId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ConfigureRequest(bookId.ToString(), libraryId);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
BuildExpectedEndpoint(libraryId, bookId),
|
||||
Arg.Any<CancellationToken>());
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.False(jsonDocument.RootElement.TryGetProperty("data", out JsonElement _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenBookIdIsNotParseable_ShouldForwardGuidEmptyBookIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ConfigureRequest("not-a-guid", libraryId);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
BuildExpectedEndpoint(libraryId, Guid.Empty),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenBookIdIsMissing_ShouldForwardGuidEmptyBookIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={libraryId}");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
BuildExpectedEndpoint(libraryId, Guid.Empty),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenLibraryQueryIdIsNotParseable_ShouldForwardGuidEmptyLibraryIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid bookId = Guid.NewGuid();
|
||||
ConfigureRequest(bookId.ToString(), "not-a-guid");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
BuildExpectedEndpoint(Guid.Empty, bookId),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the route and query values the endpoint reads the book identity from.
|
||||
/// </summary>
|
||||
/// <param name="bookId">The raw route value of the book Id.</param>
|
||||
/// <param name="libraryId">The raw query value of the library Id.</param>
|
||||
private void ConfigureRequest(string bookId, Guid libraryId)
|
||||
{
|
||||
ConfigureRequest(bookId, libraryId.ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the route and query values the endpoint reads the book identity from.
|
||||
/// </summary>
|
||||
/// <param name="bookId">The raw route value of the book Id.</param>
|
||||
/// <param name="libraryId">The raw query value of the library Id.</param>
|
||||
private void ConfigureRequest(string bookId, string libraryId)
|
||||
{
|
||||
_sut.HttpContext.Request.RouteValues["bookId"] = bookId;
|
||||
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={libraryId}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the upstream endpoint the book deletion is expected to be sent to.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The normalized Id of the media library.</param>
|
||||
/// <param name="bookId">The normalized Id of the book.</param>
|
||||
/// <returns>The expected upstream endpoint.</returns>
|
||||
private static string BuildExpectedEndpoint(Guid libraryId, Guid bookId)
|
||||
{
|
||||
return ApiRoutes.Books.DELETE_BOOK
|
||||
.Replace("{libraryId}", libraryId.ToString())
|
||||
.Replace("{bookId}", bookId.ToString());
|
||||
}
|
||||
}
|
||||
+183
@@ -0,0 +1,183 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Common.DTO.Themes;
|
||||
using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Presentation.Web.Common.Http;
|
||||
using Lumina.Presentation.Web.Common.Primitives;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Common.Services;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeletedBooks;
|
||||
using Lumina.Presentation.Web.Core.Themes;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Antiforgery;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using Microsoft.Extensions.Localization;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Reflection;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeletedBooks;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="DeletedBooksViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeletedBooksViewEndpointTests
|
||||
{
|
||||
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 DeletedBooksViewEndpoint _sut;
|
||||
private readonly LibraryDtoFixture _libraryDtoFixture = new();
|
||||
private readonly DeletedBookDtoFixture _deletedBookDtoFixture = new();
|
||||
private readonly GetBooksViewRequestFixture _getBooksViewRequestFixture = new();
|
||||
private readonly ThemePageRenderResultDtoFixture _themePageRenderResultDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeletedBooksViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public DeletedBooksViewEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_mockUrlService = Substitute.For<IUrlService>();
|
||||
_mockThemePageRenderer = Substitute.For<ThemePageRenderer>(new ThemeService(_mockApiHttpClient), new ThemeTemplateEngine());
|
||||
_mockAntiforgery = Substitute.For<IAntiforgery>();
|
||||
_mockAntiforgery.GetAndStoreTokens(Arg.Any<HttpContext>())
|
||||
.Returns(new AntiforgeryTokenSet("request-token", "cookie-token", "__RequestVerificationToken", "RequestVerificationToken"));
|
||||
_mockStringLocalizer = Substitute.For<IStringLocalizer>();
|
||||
_mockStringLocalizer[Arg.Any<string>()].Returns(callInfo => new LocalizedString(
|
||||
callInfo.Arg<string>(),
|
||||
callInfo.Arg<string>() == "Title" ? "Deleted items" : $"Localized-{callInfo.Arg<string>()}"));
|
||||
_mockStringLocalizer.GetAllStrings(Arg.Any<bool>()).Returns(new LocalizedString[]
|
||||
{
|
||||
new("Title", "Deleted items"),
|
||||
new("NoDeletedItems", "There are no deleted items in this library.")
|
||||
});
|
||||
_mockStringLocalizerFactory = Substitute.For<IStringLocalizerFactory>();
|
||||
_mockStringLocalizerFactory.Create(Arg.Any<string>(), Arg.Any<string>()).Returns(_mockStringLocalizer);
|
||||
_sut = Factory.Create<DeletedBooksViewEndpoint>(_mockApiHttpClient, _mockUrlService, _mockThemePageRenderer, _mockAntiforgery, _mockStringLocalizerFactory);
|
||||
TestHttpContextFactory.ConfigureSession(_sut.HttpContext, TestHttpContextFactory.CreateSession());
|
||||
_sut.HttpContext.Request.Path = "/en-us/library/written-content-library/books-library/books/deleted-items";
|
||||
|
||||
StubUrls();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenThemeRenderingSucceeds_ShouldRenderThemedViewWithDocumentedPageData()
|
||||
{
|
||||
// Arrange
|
||||
LibraryDto library = _libraryDtoFixture.Create(title: "Books");
|
||||
DeletedBookDto[] deletedBooks = [.. _deletedBookDtoFixture.CreateMany(2)];
|
||||
_mockApiHttpClient.GetAsync<LibraryDto>(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(library);
|
||||
_mockApiHttpClient.GetAsync<DeletedBookDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(deletedBooks);
|
||||
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_themePageRenderResultDtoFixture.Create(content: "<section>deleted</section>", script: "<script>deleted</script>")));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(_getBooksViewRequestFixture.Create(libraryId: library.Id), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("/Core/Views/Shared/_ThemedView.cshtml", GetRenderedViewName(result));
|
||||
await _mockThemePageRenderer.Received(1).RenderAsync(
|
||||
Arg.Is<ThemePageDto>(page =>
|
||||
page.PageKey == "library/written-content-library/book-library/books/deleted-items" &&
|
||||
page.Title == "Deleted items" &&
|
||||
string.Equals(page.PageData["libraryId"] as string, library.Id!.Value.ToString(), StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["libraryTitle"] as string, "Books", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["restoreUrl"] as string, "http://localhost/en-us/library/written-content-library/books-library/books/00000000-0000-0000-0000-000000000000/api-restore-book", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["backUrl"] as string, $"http://localhost/en-us/library/written-content-library/books-library/books?libraryId={library.Id}", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["antiforgeryToken"] as string, "request-token", StringComparison.Ordinal) &&
|
||||
page.PageData.ContainsKey("deletedBooksJson") &&
|
||||
page.PageData.ContainsKey("strings") &&
|
||||
page.PageData.ContainsKey("stringsJson")),
|
||||
Arg.Is<string?>(requestedThemeId => requestedThemeId == null),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenLibraryIdIsNull_ShouldRedirectToHome()
|
||||
{
|
||||
// Arrange
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Home.INDEX_CULTURED).Returns("http://localhost/en-us");
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(_getBooksViewRequestFixture.Create(libraryId: null), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
RedirectHttpResult redirectResult = Assert.IsType<RedirectHttpResult>(result);
|
||||
Assert.Equal("http://localhost/en-us", redirectResult.Url);
|
||||
await _mockApiHttpClient.DidNotReceive().GetAsync<LibraryDto>(Arg.Any<string>(), Arg.Any<CancellationToken>());
|
||||
await _mockThemePageRenderer.DidNotReceive().RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenThemeRenderingFails_ShouldFallBackToTheRazorViewWithTheDeletedBooks()
|
||||
{
|
||||
// Arrange
|
||||
LibraryDto library = _libraryDtoFixture.Create(title: "Books");
|
||||
DeletedBookDto[] deletedBooks = [.. _deletedBookDtoFixture.CreateMany(2)];
|
||||
_mockApiHttpClient.GetAsync<LibraryDto>(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(library);
|
||||
_mockApiHttpClient.GetAsync<DeletedBookDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(deletedBooks);
|
||||
_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(_getBooksViewRequestFixture.Create(libraryId: library.Id), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/DeletedItems.cshtml", GetRenderedViewName(result));
|
||||
DeletedBooksPageDto model = Assert.IsType<DeletedBooksPageDto>(GetRenderedModel(result));
|
||||
Assert.Equal(library.Id, model.Library.Id);
|
||||
Assert.Equal(deletedBooks, model.DeletedBooks);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the absolute URLs that the endpoint resolves for the deleted items page.
|
||||
/// </summary>
|
||||
private void StubUrls()
|
||||
{
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Books.INDEX).Returns("http://localhost/en-us/library/written-content-library/books-library/books");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Books.RESTORE_BOOK, Arg.Any<object?>())
|
||||
.Returns("http://localhost/en-us/library/written-content-library/books-library/books/00000000-0000-0000-0000-000000000000/api-restore-book");
|
||||
}
|
||||
|
||||
/// <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);
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBookDetails;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBookDetails;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetBookDetailsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetBookDetailsEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly GetBookDetailsEndpoint _sut;
|
||||
private readonly GetBookRequestFixture _getBookRequestFixture = new();
|
||||
private readonly BookDetailsDtoFixture _bookDetailsDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetBookDetailsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetBookDetailsEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<GetBookDetailsEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldRequestBookDetailsFromApi()
|
||||
{
|
||||
// Arrange
|
||||
GetBookRequest request = _getBookRequestFixture.Create();
|
||||
BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create(id: Guid.Parse(request.BookId));
|
||||
_mockApiHttpClient.GetAsync<BookDetailsDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedBook);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<BookDetailsDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Books.GET_BOOK.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{bookId}", request.BookId)),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsBookDetails_ShouldReturnSuccessJsonWithBook()
|
||||
{
|
||||
// Arrange
|
||||
GetBookRequest request = _getBookRequestFixture.Create();
|
||||
BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create(id: Guid.Parse(request.BookId));
|
||||
_mockApiHttpClient.GetAsync<BookDetailsDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedBook);
|
||||
|
||||
// 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());
|
||||
Assert.Equal(expectedBook.Id, jsonDocument.RootElement.GetProperty("data").GetProperty("id").GetGuid());
|
||||
}
|
||||
}
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Common.Enums.Common;
|
||||
using Lumina.Presentation.Web.Common.Requests.Libraries;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetLibraryItems;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Libraries;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
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.Library.WrittenContentLibrary.BookLibrary.Books.GetLibraryItems;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetLibraryItemsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetLibraryItemsEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly GetLibraryItemsEndpoint _sut;
|
||||
private readonly GetBooksLiteRequestFixture _getBooksLiteRequestFixture = new();
|
||||
private readonly PaginatedDtoFixture<BookLiteDto> _paginatedBookLiteDtoFixture = new();
|
||||
private readonly BookLiteDtoFixture _bookLiteDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetLibraryItemsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetLibraryItemsEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<GetLibraryItemsEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldRequestLibraryItemsWithQueryParameters()
|
||||
{
|
||||
// Arrange
|
||||
GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create(
|
||||
currentPage: 2,
|
||||
perPage: 48,
|
||||
searchTerm: "the hobbit",
|
||||
filterAlphaKey: "H",
|
||||
shouldIgnoreThePrefixForAlphaPicker: true,
|
||||
sortBy: "title",
|
||||
sortOrder: SortOrder.Ascending);
|
||||
_mockApiHttpClient.GetAsync<PaginatedDto<BookLiteDto>>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedBookLiteDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedDto<BookLiteDto>>(
|
||||
Arg.Is<string>(endpoint =>
|
||||
endpoint.StartsWith(ApiRoutes.Books.GET_BOOKS_LITE.Replace("{libraryId}", request.LibraryId.ToString()), StringComparison.OrdinalIgnoreCase) &&
|
||||
endpoint.Contains("currentPage=2") &&
|
||||
endpoint.Contains("perPage=48") &&
|
||||
endpoint.Contains("searchTerm=the%20hobbit") &&
|
||||
endpoint.Contains("filterAlphaKey=H") &&
|
||||
endpoint.Contains("shouldIgnoreThePrefixForAlphaPicker=True") &&
|
||||
endpoint.Contains("sortBy=title") &&
|
||||
endpoint.Contains("sortOrder=Ascending")),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalledWithOnlyLibraryId_ShouldRequestWithoutOptionalParameters()
|
||||
{
|
||||
// Arrange
|
||||
GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create();
|
||||
_mockApiHttpClient.GetAsync<PaginatedDto<BookLiteDto>>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedBookLiteDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedDto<BookLiteDto>>(
|
||||
Arg.Is<string>(endpoint =>
|
||||
endpoint.StartsWith(ApiRoutes.Books.GET_BOOKS_LITE.Replace("{libraryId}", request.LibraryId.ToString()), StringComparison.OrdinalIgnoreCase) &&
|
||||
endpoint.EndsWith("?shouldIgnoreThePrefixForAlphaPicker=False", StringComparison.OrdinalIgnoreCase) &&
|
||||
!endpoint.Contains("currentPage=") &&
|
||||
!endpoint.Contains("searchTerm=") &&
|
||||
!endpoint.Contains("sortBy=")),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsPaginatedItems_ShouldReturnSuccessJsonWithItems()
|
||||
{
|
||||
// Arrange
|
||||
GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create();
|
||||
PaginatedDto<BookLiteDto> expectedResponse = _paginatedBookLiteDtoFixture.Create(
|
||||
data: [_bookLiteDtoFixture.Create(title: "Test Book")],
|
||||
currentPage: 1,
|
||||
perPage: 48,
|
||||
count: 1,
|
||||
numberOfPages: 1);
|
||||
_mockApiHttpClient.GetAsync<PaginatedDto<BookLiteDto>>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedResponse);
|
||||
|
||||
// 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(1, data.GetProperty("currentPage").GetInt32());
|
||||
Assert.Equal(1, data.GetProperty("data").GetArrayLength());
|
||||
}
|
||||
}
|
||||
+142
@@ -0,0 +1,142 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Common.DTO.Themes;
|
||||
using Lumina.Presentation.Web.Common.Http;
|
||||
using Lumina.Presentation.Web.Common.Primitives;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Common.Services;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Index;
|
||||
using Lumina.Presentation.Web.Core.Themes;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using Microsoft.Extensions.Localization;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Index;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="BooksIndexViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class BooksIndexViewEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly IUrlService _mockUrlService;
|
||||
private readonly ThemePageRenderer _mockThemePageRenderer;
|
||||
private readonly IStringLocalizerFactory _mockStringLocalizerFactory;
|
||||
private readonly IStringLocalizer _mockStringLocalizer;
|
||||
private readonly BooksIndexViewEndpoint _sut;
|
||||
private readonly LibraryDtoFixture _libraryDtoFixture = new();
|
||||
private readonly GetBooksViewRequestFixture _getBooksViewRequestFixture = new();
|
||||
private readonly ThemePageRenderResultDtoFixture _themePageRenderResultDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="BooksIndexViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public BooksIndexViewEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_mockUrlService = Substitute.For<IUrlService>();
|
||||
_mockThemePageRenderer = Substitute.For<ThemePageRenderer>(new ThemeService(_mockApiHttpClient), new ThemeTemplateEngine());
|
||||
_mockStringLocalizer = Substitute.For<IStringLocalizer>();
|
||||
_mockStringLocalizer.GetAllStrings(Arg.Any<bool>()).Returns(new LocalizedString[] { new("Search", "Search") });
|
||||
_mockStringLocalizerFactory = Substitute.For<IStringLocalizerFactory>();
|
||||
_mockStringLocalizerFactory.Create(Arg.Any<string>(), Arg.Any<string>()).Returns(_mockStringLocalizer);
|
||||
_sut = Factory.Create<BooksIndexViewEndpoint>(_mockApiHttpClient, _mockUrlService, _mockThemePageRenderer, _mockStringLocalizerFactory);
|
||||
TestHttpContextFactory.ConfigureSession(_sut.HttpContext, TestHttpContextFactory.CreateSession());
|
||||
_sut.HttpContext.Request.Path = "/en-us/library/written-content-library/books-library/books";
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenLibraryIdIsNull_ShouldRedirectToHome()
|
||||
{
|
||||
// Arrange
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Home.INDEX_CULTURED).Returns("http://localhost/en-us");
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(_getBooksViewRequestFixture.Create(libraryId: null), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
RedirectHttpResult redirectResult = Assert.IsType<RedirectHttpResult>(result);
|
||||
Assert.Equal("http://localhost/en-us", redirectResult.Url);
|
||||
await _mockApiHttpClient.DidNotReceive().GetAsync<LibraryDto>(Arg.Any<string>(), Arg.Any<CancellationToken>());
|
||||
await _mockThemePageRenderer.DidNotReceive().RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenLibraryIdProvided_ShouldRenderThemedPageThroughTheSharedView()
|
||||
{
|
||||
// Arrange
|
||||
LibraryDto expectedLibrary = _libraryDtoFixture.Create();
|
||||
_mockApiHttpClient.GetAsync<LibraryDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedLibrary);
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Books.GET_LIBRARY_ITEMS).Returns("http://localhost/en-us/library/written-content-library/books-library/books/api-get-library-items");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Settings.GET_USER_SETTINGS).Returns("http://localhost/en-us/tools/settings/api-get-user-settings");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Books.READ, Arg.Any<object>()).Returns("http://localhost/en-us/library/written-content-library/books-library/books/00000000-0000-0000-0000-000000000000/read");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Books.DELETE_BOOK, Arg.Any<object>()).Returns("http://localhost/en-us/library/written-content-library/books-library/books/00000000-0000-0000-0000-000000000000/api-delete-book");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Books.DELETED_BOOKS).Returns("http://localhost/en-us/library/written-content-library/books-library/books/deleted-items");
|
||||
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_themePageRenderResultDtoFixture.Create(content: "<section>content</section>", script: "<script>script</script>")));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(_getBooksViewRequestFixture.Create(libraryId: expectedLibrary.Id), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.IsType<RazorViewResult>(result);
|
||||
await _mockThemePageRenderer.Received(1).RenderAsync(
|
||||
Arg.Is<ThemePageDto>(page =>
|
||||
page.PageKey == "library/written-content-library/book-library/books/index" &&
|
||||
page.Title == expectedLibrary.Title &&
|
||||
page.PageData.ContainsKey("libraryId") &&
|
||||
page.PageData.ContainsKey("settingsUrl") &&
|
||||
page.PageData.ContainsKey("strings") &&
|
||||
page.PageData.ContainsKey("stringsJson") &&
|
||||
string.Equals(
|
||||
page.PageData["itemsUrl"] as string,
|
||||
"http://localhost/en-us/library/written-content-library/books-library/books/api-get-library-items",
|
||||
StringComparison.Ordinal) &&
|
||||
string.Equals(
|
||||
page.PageData["readUrl"] as string,
|
||||
"http://localhost/en-us/library/written-content-library/books-library/books/00000000-0000-0000-0000-000000000000/read",
|
||||
StringComparison.Ordinal) &&
|
||||
string.Equals(
|
||||
page.PageData["deleteUrl"] as string,
|
||||
"http://localhost/en-us/library/written-content-library/books-library/books/00000000-0000-0000-0000-000000000000/api-delete-book",
|
||||
StringComparison.Ordinal) &&
|
||||
string.Equals(
|
||||
page.PageData["deletedBooksUrl"] as string,
|
||||
"http://localhost/en-us/library/written-content-library/books-library/books/deleted-items",
|
||||
StringComparison.Ordinal)),
|
||||
Arg.Is<string?>(requestedThemeId => requestedThemeId == null),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenThemeRenderingFails_ShouldFallBackToRazorView()
|
||||
{
|
||||
// Arrange
|
||||
LibraryDto expectedLibrary = _libraryDtoFixture.Create();
|
||||
_mockApiHttpClient.GetAsync<LibraryDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedLibrary);
|
||||
_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(_getBooksViewRequestFixture.Create(libraryId: expectedLibrary.Id), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.IsType<RazorViewResult>(result);
|
||||
await _mockThemePageRenderer.Received(1).RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.Reading;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingAvailability;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Reading;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingAvailability;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetReadingAvailabilityEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetReadingAvailabilityEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly GetReadingAvailabilityEndpoint _sut;
|
||||
private readonly ReadingAvailabilityDtoFixture _readingAvailabilityDtoFixture = new();
|
||||
private readonly GetBookReadingAvailabilityRequestFixture _getBookReadingAvailabilityRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetReadingAvailabilityEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetReadingAvailabilityEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<GetReadingAvailabilityEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenBookIsAvailable_ShouldReturnSuccessJson()
|
||||
{
|
||||
// Arrange
|
||||
GetBookReadingAvailabilityRequest request = _getBookReadingAvailabilityRequestFixture.Create();
|
||||
ReadingAvailabilityDto availability = _readingAvailabilityDtoFixture.Create(bookId: request.BookId, isAvailable: true);
|
||||
_mockApiHttpClient.GetAsync<ReadingAvailabilityDto>(ApiRoutes.Books.GET_BOOK_READING_AVAILABILITY.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{bookId}", request.BookId.ToString()), Arg.Any<CancellationToken>())
|
||||
.Returns(availability);
|
||||
|
||||
// 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());
|
||||
Assert.Equal(availability.LibraryId, jsonDocument.RootElement.GetProperty("libraryId").GetGuid());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenBookIsNotAvailable_ShouldReturnUnavailableJsonWithErrorCode()
|
||||
{
|
||||
// Arrange
|
||||
GetBookReadingAvailabilityRequest request = _getBookReadingAvailabilityRequestFixture.Create();
|
||||
ReadingAvailabilityDto availability = _readingAvailabilityDtoFixture.Create(bookId: request.BookId, isAvailable: false, errorCode: "ReaderDisabled");
|
||||
_mockApiHttpClient.GetAsync<ReadingAvailabilityDto>(ApiRoutes.Books.GET_BOOK_READING_AVAILABILITY.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{bookId}", request.BookId.ToString()), Arg.Any<CancellationToken>())
|
||||
.Returns(availability);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.False(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal("ReaderDisabled", jsonDocument.RootElement.GetProperty("errorCode").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldRequestReadingAvailabilityFromApi()
|
||||
{
|
||||
// Arrange
|
||||
GetBookReadingAvailabilityRequest request = _getBookReadingAvailabilityRequestFixture.Create();
|
||||
ReadingAvailabilityDto availability = _readingAvailabilityDtoFixture.Create(bookId: request.BookId, isAvailable: true);
|
||||
_mockApiHttpClient.GetAsync<ReadingAvailabilityDto>(ApiRoutes.Books.GET_BOOK_READING_AVAILABILITY.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{bookId}", request.BookId.ToString()), Arg.Any<CancellationToken>())
|
||||
.Returns(availability);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<ReadingAvailabilityDto>(ApiRoutes.Books.GET_BOOK_READING_AVAILABILITY.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{bookId}", request.BookId.ToString()), Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+131
@@ -0,0 +1,131 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.Reading;
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingManifest;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Reading;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingManifest;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetReadingManifestEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetReadingManifestEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly GetReadingManifestEndpoint _sut;
|
||||
private readonly GetBookReadingManifestRequestFixture _getBookReadingManifestRequestFixture = new();
|
||||
private readonly ReadingManifestDtoFixture _readingManifestDtoFixture = new();
|
||||
private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetReadingManifestEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetReadingManifestEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<GetReadingManifestEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnSuccessJsonWithManifest()
|
||||
{
|
||||
// Arrange
|
||||
GetBookReadingManifestRequest request = _getBookReadingManifestRequestFixture.Create();
|
||||
ReadingManifestDto manifest = _readingManifestDtoFixture.Create();
|
||||
_mockApiHttpClient.GetAsync<ReadingManifestDto>(ApiRoutes.Books.GET_BOOK_READING_MANIFEST.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{bookId}", request.BookId.ToString()), Arg.Any<CancellationToken>())
|
||||
.Returns(manifest);
|
||||
|
||||
// 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());
|
||||
Assert.Equal(manifest.Title, jsonDocument.RootElement.GetProperty("data").GetProperty("title").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsNoReaderAvailable_ShouldReturnDistinctErrorCodeJson()
|
||||
{
|
||||
// Arrange
|
||||
GetBookReadingManifestRequest request = _getBookReadingManifestRequestFixture.Create();
|
||||
_mockApiHttpClient.GetAsync<ReadingManifestDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns<Task<ReadingManifestDto>>(_ => throw new ApiException(_problemDetailsDtoFixture.Create(detail: "NoReaderAvailable"), HttpStatusCode.NotFound));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.False(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal("NoReaderAvailable", jsonDocument.RootElement.GetProperty("errorCode").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsReaderDisabled_ShouldReturnDistinctErrorCodeJson()
|
||||
{
|
||||
// Arrange
|
||||
GetBookReadingManifestRequest request = _getBookReadingManifestRequestFixture.Create();
|
||||
_mockApiHttpClient.GetAsync<ReadingManifestDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns<Task<ReadingManifestDto>>(_ => throw new ApiException(_problemDetailsDtoFixture.Create(detail: "ReaderDisabled"), HttpStatusCode.NotFound));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.False(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal("ReaderDisabled", jsonDocument.RootElement.GetProperty("errorCode").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsUnrelatedError_ShouldRethrow()
|
||||
{
|
||||
// Arrange
|
||||
GetBookReadingManifestRequest request = _getBookReadingManifestRequestFixture.Create();
|
||||
_mockApiHttpClient.GetAsync<ReadingManifestDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns<Task<ReadingManifestDto>>(_ => throw new ApiException(_problemDetailsDtoFixture.Create(detail: "BookNotFound"), HttpStatusCode.NotFound));
|
||||
|
||||
// Act
|
||||
Func<Task<IResult>> act = () => _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAsync<ApiException>(act);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldRequestReadingManifestFromApi()
|
||||
{
|
||||
// Arrange
|
||||
GetBookReadingManifestRequest request = _getBookReadingManifestRequestFixture.Create();
|
||||
ReadingManifestDto manifest = _readingManifestDtoFixture.Create();
|
||||
_mockApiHttpClient.GetAsync<ReadingManifestDto>(ApiRoutes.Books.GET_BOOK_READING_MANIFEST.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{bookId}", request.BookId.ToString()), Arg.Any<CancellationToken>())
|
||||
.Returns(manifest);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<ReadingManifestDto>(ApiRoutes.Books.GET_BOOK_READING_MANIFEST.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{bookId}", request.BookId.ToString()), Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.FileSystemManagement;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingResource;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingResource;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetReadingResourceEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetReadingResourceEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly GetReadingResourceEndpoint _sut;
|
||||
private readonly GetBookReadingResourceRequestFixture _getBookReadingResourceRequestFixture = new();
|
||||
private readonly BlobDataDtoFixture _blobDataDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetReadingResourceEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetReadingResourceEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<GetReadingResourceEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnBytesResultWithResourceData()
|
||||
{
|
||||
// Arrange
|
||||
GetBookReadingResourceRequest request = _getBookReadingResourceRequestFixture.Create();
|
||||
BlobDataDto blob = _blobDataDtoFixture.Create(contentType: "image/png");
|
||||
_mockApiHttpClient.GetBlobAsync(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(blob);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
FileContentHttpResult bytesResult = Assert.IsType<FileContentHttpResult>(result);
|
||||
Assert.Equal(blob.Data, bytesResult.FileContents);
|
||||
Assert.Equal(blob.ContentType, bytesResult.ContentType);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldRequestReadingResourceFromApi()
|
||||
{
|
||||
// Arrange
|
||||
GetBookReadingResourceRequest request = _getBookReadingResourceRequestFixture.Create();
|
||||
BlobDataDto blob = _blobDataDtoFixture.Create();
|
||||
_mockApiHttpClient.GetBlobAsync(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(blob);
|
||||
string expectedEndpoint = ApiRoutes.Books.GET_BOOK_READING_RESOURCE
|
||||
.Replace("{libraryId}", request.LibraryId.ToString())
|
||||
.Replace("{bookId}", request.BookId.ToString())
|
||||
.Replace("{resourceKey}", Uri.EscapeDataString(request.ResourceKey));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetBlobAsync(expectedEndpoint, Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.Reading;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingSection;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Reading;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingSection;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetReadingSectionEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetReadingSectionEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly GetReadingSectionEndpoint _sut;
|
||||
private readonly GetBookReadingSectionRequestFixture _getBookReadingSectionRequestFixture = new();
|
||||
private readonly ReadingSectionDtoFixture _readingSectionDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetReadingSectionEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetReadingSectionEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<GetReadingSectionEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnSuccessJsonWithSection()
|
||||
{
|
||||
// Arrange
|
||||
GetBookReadingSectionRequest request = _getBookReadingSectionRequestFixture.Create();
|
||||
ReadingSectionDto section = _readingSectionDtoFixture.Create(locationRef: request.LocationRef);
|
||||
_mockApiHttpClient.GetAsync<ReadingSectionDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(section);
|
||||
|
||||
// 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());
|
||||
Assert.Equal(section.LocationRef, jsonDocument.RootElement.GetProperty("data").GetProperty("locationRef").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldRequestReadingSectionFromApi()
|
||||
{
|
||||
// Arrange
|
||||
GetBookReadingSectionRequest request = _getBookReadingSectionRequestFixture.Create();
|
||||
ReadingSectionDto section = _readingSectionDtoFixture.Create(locationRef: request.LocationRef);
|
||||
_mockApiHttpClient.GetAsync<ReadingSectionDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(section);
|
||||
string expectedEndpoint = ApiRoutes.Books.GET_BOOK_READING_SECTION
|
||||
.Replace("{libraryId}", request.LibraryId.ToString())
|
||||
.Replace("{bookId}", request.BookId.ToString())
|
||||
.Replace("{locationRef}", Uri.EscapeDataString(request.LocationRef));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<ReadingSectionDto>(expectedEndpoint, Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Http;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.Read;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.Read;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ReadViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ReadViewEndpointTests
|
||||
{
|
||||
private readonly ReadViewEndpoint _sut = Factory.Create<ReadViewEndpoint>();
|
||||
private readonly ReadBookViewRequestFixture _readBookViewRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ReadViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public ReadViewEndpointTests()
|
||||
{
|
||||
TestHttpContextFactory.ConfigureSession(_sut.HttpContext, TestHttpContextFactory.CreateSession());
|
||||
_sut.HttpContext.Request.Path = "/en-us/library/written-content-library/books-library/books/00000000-0000-0000-0000-000000000000/read";
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldReturnTheReadRazorView()
|
||||
{
|
||||
// Arrange
|
||||
ReadBookViewRequest request = _readBookViewRequestFixture.Create();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.IsType<RazorViewResult>(result);
|
||||
}
|
||||
}
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.RestoreBook;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.RestoreBook;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="RestoreBookEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RestoreBookEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly RestoreBookEndpoint _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RestoreBookEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public RestoreBookEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<RestoreBookEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldRestoreBookViaApiAndReturnSuccessPayload()
|
||||
{
|
||||
// Arrange
|
||||
Guid bookId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ConfigureRequest(bookId.ToString(), libraryId);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync(
|
||||
BuildExpectedEndpoint(libraryId, bookId),
|
||||
Arg.Any<CancellationToken>());
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("data").GetProperty("isRestored").GetBoolean());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenBookIdIsNotParseable_ShouldForwardGuidEmptyBookIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ConfigureRequest("not-a-guid", libraryId);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync(
|
||||
BuildExpectedEndpoint(libraryId, Guid.Empty),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenLibraryQueryIdIsNotParseable_ShouldForwardGuidEmptyLibraryIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid bookId = Guid.NewGuid();
|
||||
ConfigureRequest(bookId.ToString(), "not-a-guid");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync(
|
||||
BuildExpectedEndpoint(Guid.Empty, bookId),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the route and query values the endpoint reads the book identity from.
|
||||
/// </summary>
|
||||
/// <param name="bookId">The raw route value of the book Id.</param>
|
||||
/// <param name="libraryId">The raw query value of the library Id.</param>
|
||||
private void ConfigureRequest(string bookId, Guid libraryId)
|
||||
{
|
||||
ConfigureRequest(bookId, libraryId.ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the route and query values the endpoint reads the book identity from.
|
||||
/// </summary>
|
||||
/// <param name="bookId">The raw route value of the book Id.</param>
|
||||
/// <param name="libraryId">The raw query value of the library Id.</param>
|
||||
private void ConfigureRequest(string bookId, string libraryId)
|
||||
{
|
||||
_sut.HttpContext.Request.RouteValues["bookId"] = bookId;
|
||||
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={libraryId}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the upstream endpoint the book restoration is expected to be sent to.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The normalized Id of the media library.</param>
|
||||
/// <param name="bookId">The normalized Id of the book.</param>
|
||||
/// <returns>The expected upstream endpoint.</returns>
|
||||
private static string BuildExpectedEndpoint(Guid libraryId, Guid bookId)
|
||||
{
|
||||
return ApiRoutes.Books.RESTORE_BOOK
|
||||
.Replace("{libraryId}", libraryId.ToString())
|
||||
.Replace("{bookId}", bookId.ToString());
|
||||
}
|
||||
}
|
||||
+168
@@ -0,0 +1,168 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.SaveBook;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.SaveBook;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="SaveBookEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SaveBookEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly SaveBookEndpoint _sut;
|
||||
private readonly UpdateBookRequestFixture _updateBookRequestFixture = new();
|
||||
private readonly BookDetailsDtoFixture _bookDetailsDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SaveBookEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public SaveBookEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<SaveBookEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalledWithMatchingRouteId_ShouldForwardUpdateBookRequestToApi()
|
||||
{
|
||||
// Arrange
|
||||
string routeId = Guid.NewGuid().ToString();
|
||||
UpdateBookRequest request = _updateBookRequestFixture.Create();
|
||||
string originalBookId = request.BookId!;
|
||||
BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create();
|
||||
_mockApiHttpClient.PutAsync<BookDetailsDto, UpdateBookRequest>(Arg.Any<string>(), Arg.Any<UpdateBookRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedBook);
|
||||
ConfigureRequest(routeId);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutAsync<BookDetailsDto, UpdateBookRequest>(
|
||||
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Books.UPDATE_BOOK.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{bookId}", routeId)),
|
||||
Arg.Is<UpdateBookRequest>(forwardedRequest => forwardedRequest.BookId == routeId),
|
||||
Arg.Any<CancellationToken>());
|
||||
Assert.Equal(originalBookId, request.BookId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteIdDiffersFromBodyId_ShouldForwardTheRouteIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
string routeId = Guid.NewGuid().ToString();
|
||||
string bodyId = Guid.NewGuid().ToString();
|
||||
UpdateBookRequest request = _updateBookRequestFixture.Create() with { BookId = bodyId };
|
||||
BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create();
|
||||
_mockApiHttpClient.PutAsync<BookDetailsDto, UpdateBookRequest>(Arg.Any<string>(), Arg.Any<UpdateBookRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedBook);
|
||||
ConfigureRequest(routeId);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutAsync<BookDetailsDto, UpdateBookRequest>(
|
||||
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Books.UPDATE_BOOK.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{bookId}", routeId)),
|
||||
Arg.Is<UpdateBookRequest>(forwardedRequest => forwardedRequest.BookId == routeId && forwardedRequest.BookId != bodyId),
|
||||
Arg.Any<CancellationToken>());
|
||||
Assert.Equal(bodyId, request.BookId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteIdIsNotParseable_ShouldForwardGuidEmptyToApi()
|
||||
{
|
||||
// Arrange
|
||||
const string ROUTE_ID = "not-a-guid";
|
||||
string expectedId = Guid.Empty.ToString();
|
||||
UpdateBookRequest request = _updateBookRequestFixture.Create();
|
||||
BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create();
|
||||
_mockApiHttpClient.PutAsync<BookDetailsDto, UpdateBookRequest>(Arg.Any<string>(), Arg.Any<UpdateBookRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedBook);
|
||||
ConfigureRequest(ROUTE_ID);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutAsync<BookDetailsDto, UpdateBookRequest>(
|
||||
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Books.UPDATE_BOOK.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{bookId}", expectedId)),
|
||||
Arg.Is<UpdateBookRequest>(forwardedRequest => forwardedRequest.BookId == expectedId),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteIdIsMissing_ShouldForwardGuidEmptyToApi()
|
||||
{
|
||||
// Arrange
|
||||
string expectedId = Guid.Empty.ToString();
|
||||
UpdateBookRequest request = _updateBookRequestFixture.Create();
|
||||
BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create();
|
||||
_mockApiHttpClient.PutAsync<BookDetailsDto, UpdateBookRequest>(Arg.Any<string>(), Arg.Any<UpdateBookRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedBook);
|
||||
ConfigureRequestWithoutId();
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutAsync<BookDetailsDto, UpdateBookRequest>(
|
||||
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Books.UPDATE_BOOK.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{bookId}", expectedId)),
|
||||
Arg.Is<UpdateBookRequest>(forwardedRequest => forwardedRequest.BookId == expectedId),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsUpdatedBook_ShouldReturnSuccessJsonWithBook()
|
||||
{
|
||||
// Arrange
|
||||
string routeId = Guid.NewGuid().ToString();
|
||||
UpdateBookRequest request = _updateBookRequestFixture.Create();
|
||||
BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create();
|
||||
_mockApiHttpClient.PutAsync<BookDetailsDto, UpdateBookRequest>(Arg.Any<string>(), Arg.Any<UpdateBookRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedBook);
|
||||
ConfigureRequest(routeId);
|
||||
|
||||
// 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());
|
||||
Assert.Equal(expectedBook.Id, jsonDocument.RootElement.GetProperty("data").GetProperty("id").GetGuid());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the <c>bookId</c> route value the endpoint reads the book Id from.
|
||||
/// </summary>
|
||||
/// <param name="routeId">The raw route value of the book Id.</param>
|
||||
private void ConfigureRequest(string routeId)
|
||||
{
|
||||
_sut.HttpContext.Request.RouteValues["bookId"] = routeId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Leaves the <c>bookId</c> route value unset.
|
||||
/// </summary>
|
||||
private void ConfigureRequestWithoutId()
|
||||
{
|
||||
_sut.HttpContext.Request.RouteValues.Remove("bookId");
|
||||
}
|
||||
}
|
||||
+183
@@ -0,0 +1,183 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBookCover;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.Features;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBookCover;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="UpdateBookCoverEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateBookCoverEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly UpdateBookCoverEndpoint _sut;
|
||||
private readonly UpdateBookCoverDtoFixture _updateBookCoverDtoFixture = new();
|
||||
private static readonly Guid s_libraryId = Guid.NewGuid();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateBookCoverEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public UpdateBookCoverEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<UpdateBookCoverEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalledWithFile_ShouldUploadCoverToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid bookId = Guid.NewGuid();
|
||||
_mockApiHttpClient.PutMultipartAsync<UpdateBookCoverDto>(Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_updateBookCoverDtoFixture.Create(coverPath: "/media/books/cover.jpg"));
|
||||
ConfigureRequest(bookId, [1, 2, 3], "cover.jpg");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutMultipartAsync<UpdateBookCoverDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Books.UPDATE_BOOK_COVER.Replace("{libraryId}", s_libraryId.ToString()).Replace("{bookId}", bookId.ToString())),
|
||||
Arg.Any<Stream>(),
|
||||
Arg.Is<string>(fileName => fileName == "cover.jpg"),
|
||||
Arg.Is<string>(fieldName => fieldName == "cover"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteIdIsNotParseable_ShouldUploadCoverWithEmptyBookId()
|
||||
{
|
||||
// Arrange
|
||||
_mockApiHttpClient.PutMultipartAsync<UpdateBookCoverDto>(Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_updateBookCoverDtoFixture.Create(coverPath: "/media/books/cover.jpg"));
|
||||
ConfigureRequest("not-a-guid", [1, 2, 3], "cover.jpg");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutMultipartAsync<UpdateBookCoverDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Books.UPDATE_BOOK_COVER.Replace("{libraryId}", s_libraryId.ToString()).Replace("{bookId}", Guid.Empty.ToString())),
|
||||
Arg.Any<Stream>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsCoverPath_ShouldReturnSuccessJsonWithPath()
|
||||
{
|
||||
// Arrange
|
||||
Guid bookId = Guid.NewGuid();
|
||||
string expectedPath = "/media/books/cover.jpg";
|
||||
_mockApiHttpClient.PutMultipartAsync<UpdateBookCoverDto>(Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_updateBookCoverDtoFixture.Create(coverPath: expectedPath));
|
||||
ConfigureRequest(bookId, [1, 2, 3], "cover.jpg");
|
||||
|
||||
// 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.Equal(expectedPath, jsonDocument.RootElement.GetProperty("data").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenFormHasNoFile_ShouldForwardRequestWithoutFileToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid bookId = Guid.NewGuid();
|
||||
string expectedPath = "/media/books/cover.jpg";
|
||||
_mockApiHttpClient.PutMultipartAsync<UpdateBookCoverDto>(Arg.Any<string>(), Arg.Any<Stream?>(), Arg.Any<string?>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_updateBookCoverDtoFixture.Create(coverPath: expectedPath));
|
||||
ConfigureRequestWithoutFiles(bookId);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutMultipartAsync<UpdateBookCoverDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Books.UPDATE_BOOK_COVER.Replace("{libraryId}", s_libraryId.ToString()).Replace("{bookId}", bookId.ToString())),
|
||||
Arg.Is<Stream?>(stream => stream == null),
|
||||
Arg.Is<string?>(fileName => fileName == null),
|
||||
Arg.Is<string>(fieldName => fieldName == "cover"),
|
||||
Arg.Any<CancellationToken>());
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(expectedPath, jsonDocument.RootElement.GetProperty("data").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRequestIsNotMultipart_ShouldForwardRequestWithoutFileToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid bookId = Guid.NewGuid();
|
||||
string expectedPath = "/media/books/cover.jpg";
|
||||
_mockApiHttpClient.PutMultipartAsync<UpdateBookCoverDto>(Arg.Any<string>(), Arg.Any<Stream?>(), Arg.Any<string?>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_updateBookCoverDtoFixture.Create(coverPath: expectedPath));
|
||||
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
|
||||
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={s_libraryId}");
|
||||
_sut.HttpContext.Request.ContentType = "application/json";
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutMultipartAsync<UpdateBookCoverDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Books.UPDATE_BOOK_COVER.Replace("{libraryId}", s_libraryId.ToString()).Replace("{bookId}", bookId.ToString())),
|
||||
Arg.Is<Stream?>(stream => stream == null),
|
||||
Arg.Is<string?>(fileName => fileName == null),
|
||||
Arg.Is<string>(fieldName => fieldName == "cover"),
|
||||
Arg.Any<CancellationToken>());
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(expectedPath, jsonDocument.RootElement.GetProperty("data").GetString());
|
||||
}
|
||||
|
||||
private void ConfigureRequest(Guid bookId, byte[] content, string fileName)
|
||||
{
|
||||
ConfigureRequest(bookId.ToString(), content, fileName);
|
||||
}
|
||||
|
||||
private void ConfigureRequest(string bookId, byte[] content, string fileName)
|
||||
{
|
||||
_sut.HttpContext.Request.RouteValues["bookId"] = bookId;
|
||||
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={s_libraryId}");
|
||||
MemoryStream coverStream = new(content);
|
||||
IFormFile formFile = new FormFile(coverStream, 0, content.Length, "cover", fileName);
|
||||
FormFileCollection files = [formFile];
|
||||
IFormCollection form = new FormCollection([], files);
|
||||
_sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test";
|
||||
_sut.HttpContext.Features.Set<IFormFeature>(new FormFeature(form));
|
||||
}
|
||||
|
||||
private void ConfigureRequestWithoutFiles(Guid bookId)
|
||||
{
|
||||
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
|
||||
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={s_libraryId}");
|
||||
IFormCollection form = new FormCollection([]);
|
||||
_sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test";
|
||||
_sut.HttpContext.Features.Set<IFormFeature>(new FormFeature(form));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user