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
+113
@@ -0,0 +1,113 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.DeleteMusicAlbum;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.DeleteMusicAlbum;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="DeleteMusicAlbumEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteMusicAlbumEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteMusicAlbumEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public DeleteMusicAlbumEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteMusicAlbum_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldForwardDeleteAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
_apiFactory.ApiClientStub.RegisterDeleteSuccess($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}");
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(artistId, albumId, libraryId);
|
||||
deleteRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Contains($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}", _apiFactory.ApiClientStub.DeleteEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteMusicAlbum_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(artistId, albumId, libraryId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.DoesNotContain($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}", _apiFactory.ApiClientStub.DeleteEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteMusicAlbum_WhenNotAuthenticated_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid());
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.SendAsync(deleteRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Empty(_apiFactory.ApiClientStub.DeleteEndpointsCalled);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the delete request for the album identified by the route, with the owning library passed through the query string.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The route Id of the artist the album belongs to.</param>
|
||||
/// <param name="albumId">The route Id of the album to delete.</param>
|
||||
/// <param name="libraryId">The Id of the media library the album belongs to.</param>
|
||||
/// <returns>The configured delete request.</returns>
|
||||
private static HttpRequestMessage CreateDeleteRequest(Guid artistId, Guid albumId, Guid libraryId)
|
||||
{
|
||||
HttpRequestMessage deleteRequest = new(HttpMethod.Delete, $"/en-us/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/api-delete-album?libraryId={libraryId}")
|
||||
{
|
||||
// The front-end sends the JSON content type even for DELETE requests, which triggers the antiforgery validation.
|
||||
Content = new StringContent("{}", Encoding.UTF8, "application/json")
|
||||
};
|
||||
// The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted.
|
||||
deleteRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
deleteRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
return deleteRequest;
|
||||
}
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.EditMusicAlbum;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.EditMusicAlbum;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="EditMusicAlbumViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class EditMusicAlbumViewEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly MusicAlbumDtoFixture _musicAlbumDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="EditMusicAlbumViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public EditMusicAlbumViewEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EditMusicAlbum_WhenCalledByAuthenticatedUser_ShouldRenderEditAlbumPage()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
MusicAlbumDto expectedAlbum = _musicAlbumDtoFixture.Create();
|
||||
expectedAlbum.Metadata!.Title = "An album";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{expectedAlbum.LibraryId}/artists/{expectedAlbum.ArtistId}/albums/{expectedAlbum.Id}", expectedAlbum);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/audio-library/music-library/artists/{expectedAlbum.ArtistId}/albums/{expectedAlbum.Id}?libraryId={expectedAlbum.LibraryId}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType);
|
||||
Assert.Contains("An album", content);
|
||||
}
|
||||
}
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
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.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetArtistAlbums;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetArtistAlbumsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetArtistAlbumsEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly PaginatedDtoFixture<MusicAlbumLiteDto> _paginatedMusicAlbumLiteDtoFixture = new();
|
||||
private readonly MusicAlbumLiteDtoFixture _musicAlbumLiteDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetArtistAlbumsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetArtistAlbumsEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetArtistAlbums_WhenCalledByAuthenticatedUser_ShouldReturnAlbumsFromApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
PaginatedDto<MusicAlbumLiteDto> expectedResponse = _paginatedMusicAlbumLiteDtoFixture.Create(data: [_musicAlbumLiteDtoFixture.Create(title: "Test Album")]);
|
||||
string expectedEndpoint = $"libraries/{libraryId}/artists/{artistId}/albums/lite?currentPage=1&perPage=20";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, expectedResponse);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/audio-library/music-library/artists/{artistId}/albums/api-get-albums?libraryId={libraryId}¤tPage=1&perPage=20");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(expectedResponse.Data.Count, json.RootElement.GetProperty("data").GetProperty("data").GetArrayLength());
|
||||
Assert.Contains(expectedEndpoint, _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetArtistAlbums_WhenNotAuthenticated_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.GetAsync($"/en-us/library/audio-library/music-library/artists/{Guid.NewGuid()}/albums/api-get-albums?libraryId={Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("libraries/", StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
}
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
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.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetMusicAlbum;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetMusicAlbumEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetMusicAlbumEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly MusicAlbumDtoFixture _musicAlbumDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetMusicAlbumEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetMusicAlbumEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMusicAlbum_WhenCalledByAuthenticatedUser_ShouldReturnAlbumFromApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
MusicAlbumDto expectedAlbum = _musicAlbumDtoFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}", expectedAlbum);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/api-get-album?libraryId={libraryId}");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(albumId, json.RootElement.GetProperty("data").GetProperty("id").GetGuid());
|
||||
Assert.Contains($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}", _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMusicAlbum_WhenNotAuthenticated_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.GetAsync($"/en-us/library/audio-library/music-library/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/api-get-album?libraryId={Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("libraries/", StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
}
|
||||
+113
@@ -0,0 +1,113 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.RestoreMusicAlbum;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.RestoreMusicAlbum;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="RestoreMusicAlbumEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RestoreMusicAlbumEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RestoreMusicAlbumEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public RestoreMusicAlbumEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RestoreMusicAlbum_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldForwardPostAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
_apiFactory.ApiClientStub.RegisterPostSuccess($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/restore");
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage restoreRequest = CreateRestoreRequest(artistId, albumId, libraryId);
|
||||
restoreRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(restoreRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.True(json.RootElement.GetProperty("data").GetProperty("isRestored").GetBoolean());
|
||||
Assert.Contains($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/restore", _apiFactory.ApiClientStub.PostRequests.Select(postRequest => postRequest.Endpoint));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RestoreMusicAlbum_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpRequestMessage restoreRequest = CreateRestoreRequest(Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid());
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(restoreRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Empty(_apiFactory.ApiClientStub.PostRequests);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RestoreMusicAlbum_WhenNotAuthenticated_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
HttpRequestMessage restoreRequest = CreateRestoreRequest(Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid());
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.SendAsync(restoreRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Empty(_apiFactory.ApiClientStub.PostRequests);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the restore request for the album identified by the route, with the owning library passed through the query string.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The route Id of the artist the album belongs to.</param>
|
||||
/// <param name="albumId">The route Id of the album to restore.</param>
|
||||
/// <param name="libraryId">The Id of the media library the album belongs to.</param>
|
||||
/// <returns>The configured restore request.</returns>
|
||||
private static HttpRequestMessage CreateRestoreRequest(Guid artistId, Guid albumId, Guid libraryId)
|
||||
{
|
||||
HttpRequestMessage restoreRequest = new(HttpMethod.Post, $"/en-us/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/api-restore-album?libraryId={libraryId}")
|
||||
{
|
||||
// The front-end sends the JSON content type even for bodyless POST requests, which triggers the antiforgery validation.
|
||||
Content = new StringContent("{}", Encoding.UTF8, "application/json")
|
||||
};
|
||||
// The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted.
|
||||
restoreRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
restoreRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
return restoreRequest;
|
||||
}
|
||||
}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Albums;
|
||||
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 Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.SaveMusicAlbum;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="SaveMusicAlbumEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SaveMusicAlbumEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly UpdateMusicAlbumRequestFixture _updateMusicAlbumRequestFixture = new();
|
||||
private readonly MusicAlbumDtoFixture _musicAlbumDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SaveMusicAlbumEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public SaveMusicAlbumEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveMusicAlbum_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldForwardUpdateAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
UpdateMusicAlbumRequest request = _updateMusicAlbumRequestFixture.Create();
|
||||
MusicAlbumDto expectedAlbum = _musicAlbumDtoFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId);
|
||||
_apiFactory.ApiClientStub.RegisterPutResponse($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}", expectedAlbum);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage saveRequest = CreateSaveRequest(artistId, albumId, libraryId, request);
|
||||
saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(albumId, json.RootElement.GetProperty("data").GetProperty("id").GetGuid());
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/artists/{artistId}/albums/{albumId}" && putRequest.Data is UpdateMusicAlbumRequest forwarded && forwarded.Metadata!.Title == request.Metadata!.Title && forwarded.ASIN == request.ASIN);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveMusicAlbum_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
UpdateMusicAlbumRequest request = _updateMusicAlbumRequestFixture.Create();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage saveRequest = CreateSaveRequest(artistId, albumId, libraryId, request);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/artists/{artistId}/albums/{albumId}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveMusicAlbum_WhenNotAuthenticated_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
HttpRequestMessage saveRequest = CreateSaveRequest(Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), _updateMusicAlbumRequestFixture.Create());
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.SendAsync(saveRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Empty(_apiFactory.ApiClientStub.PutRequests);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the save request that PUTs the given <paramref name="request"/> to the album identified by the route,
|
||||
/// with the owning library passed through the query string.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The route Id of the artist the album belongs to.</param>
|
||||
/// <param name="albumId">The route Id of the album to save.</param>
|
||||
/// <param name="libraryId">The Id of the media library the album belongs to.</param>
|
||||
/// <param name="request">The album data to send.</param>
|
||||
/// <returns>The configured save request.</returns>
|
||||
private static HttpRequestMessage CreateSaveRequest(Guid artistId, Guid albumId, Guid libraryId, UpdateMusicAlbumRequest request)
|
||||
{
|
||||
HttpRequestMessage saveRequest = new(HttpMethod.Put, $"/en-us/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/api-save-album?libraryId={libraryId}")
|
||||
{
|
||||
Content = JsonContent.Create(request)
|
||||
};
|
||||
saveRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
saveRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
return saveRequest;
|
||||
}
|
||||
}
|
||||
+154
@@ -0,0 +1,154 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
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.DTO.Common;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.UpdateAlbumCover;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="UpdateAlbumCoverEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateAlbumCoverEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new();
|
||||
private readonly UpdateMusicCoverDtoFixture _updateMusicCoverDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateAlbumCoverEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public UpdateAlbumCoverEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAlbumCover_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldUploadCoverAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
const string EXPECTED_PATH = "/media/albums/cover.png";
|
||||
_apiFactory.ApiClientStub.RegisterPutResponse($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/cover", _updateMusicCoverDtoFixture.Create(coverPath: EXPECTED_PATH));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage uploadRequest = CreateUploadRequest(artistId, albumId, libraryId, "cover.png");
|
||||
uploadRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(uploadRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(EXPECTED_PATH, json.RootElement.GetProperty("data").GetString());
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/cover" && putRequest.Data as string == "cover.png");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAlbumCover_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage uploadRequest = CreateUploadRequest(artistId, albumId, libraryId, "cover.png");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(uploadRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/cover");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAlbumCover_WhenCalledWithoutUploadedFile_ShouldForwardRequestAndReturnFailure()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
ProblemDetailsDto problemDetails = _problemDetailsDtoFixture.Create(title: "General.Validation", detail: "AlbumCoverCannotBeNull");
|
||||
_apiFactory.ApiClientStub.RegisterPutException($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/cover", new ApiException(problemDetails, HttpStatusCode.UnprocessableEntity, $"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/cover"));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
MultipartFormDataContent noFileForm = [];
|
||||
noFileForm.Add(new StringContent("unrelated-field"));
|
||||
HttpRequestMessage uploadRequest = new(HttpMethod.Put, $"/en-us/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/api-update-cover?libraryId={libraryId}")
|
||||
{
|
||||
Content = noFileForm
|
||||
};
|
||||
uploadRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
uploadRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(uploadRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
// The web does not short-circuit the missing file; it forwards the request, and the API reports the missing cover
|
||||
// with the same AlbumCoverCannotBeNull validation error any other client receives.
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/cover" && putRequest.Data == null);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAlbumCover_WhenNotAuthenticated_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
HttpRequestMessage uploadRequest = CreateUploadRequest(Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), "cover.png");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.SendAsync(uploadRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Empty(_apiFactory.ApiClientStub.PutRequests);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the multipart PUT request that uploads a cover to the album identified by the route.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The route Id of the artist the album belongs to.</param>
|
||||
/// <param name="albumId">The route Id of the album whose cover is uploaded.</param>
|
||||
/// <param name="libraryId">The Id of the media library the album belongs to.</param>
|
||||
/// <param name="fileName">The name of the uploaded file.</param>
|
||||
/// <returns>The configured upload request.</returns>
|
||||
private static HttpRequestMessage CreateUploadRequest(Guid artistId, Guid albumId, Guid libraryId, string fileName)
|
||||
{
|
||||
MultipartFormDataContent form = [];
|
||||
ByteArrayContent fileContent = new(Encoding.UTF8.GetBytes("fake cover payload"));
|
||||
fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
|
||||
form.Add(fileContent, "cover", fileName);
|
||||
return new HttpRequestMessage(HttpMethod.Put, $"/en-us/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/api-update-cover?libraryId={libraryId}")
|
||||
{
|
||||
Content = form
|
||||
};
|
||||
}
|
||||
}
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.DeleteMusicArtist;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.DeleteMusicArtist;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="DeleteMusicArtistEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteMusicArtistEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteMusicArtistEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public DeleteMusicArtistEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteMusicArtist_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldForwardDeleteAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
_apiFactory.ApiClientStub.RegisterDeleteSuccess($"libraries/{libraryId}/artists/{artistId}");
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(artistId, libraryId);
|
||||
deleteRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Contains($"libraries/{libraryId}/artists/{artistId}", _apiFactory.ApiClientStub.DeleteEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteMusicArtist_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(artistId, libraryId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.DoesNotContain($"libraries/{libraryId}/artists/{artistId}", _apiFactory.ApiClientStub.DeleteEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteMusicArtist_WhenNotAuthenticated_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(Guid.NewGuid(), Guid.NewGuid());
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.SendAsync(deleteRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Empty(_apiFactory.ApiClientStub.DeleteEndpointsCalled);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the delete request for the artist identified by the route, with the owning library passed through the query string.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The route Id of the artist to delete.</param>
|
||||
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
|
||||
/// <returns>The configured delete request.</returns>
|
||||
private static HttpRequestMessage CreateDeleteRequest(Guid artistId, Guid libraryId)
|
||||
{
|
||||
HttpRequestMessage deleteRequest = new(HttpMethod.Delete, $"/en-us/library/audio-library/music-library/artists/{artistId}/api-delete-artist?libraryId={libraryId}")
|
||||
{
|
||||
// The front-end sends the JSON content type even for DELETE requests, which triggers the antiforgery validation.
|
||||
Content = new StringContent("{}", Encoding.UTF8, "application/json")
|
||||
};
|
||||
// The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted.
|
||||
deleteRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
deleteRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
return deleteRequest;
|
||||
}
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.EditMusicArtist;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.EditMusicArtist;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="EditMusicArtistViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class EditMusicArtistViewEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly MusicArtistDtoFixture _musicArtistDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="EditMusicArtistViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public EditMusicArtistViewEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EditMusicArtist_WhenCalledByAuthenticatedUser_ShouldRenderEditArtistPage()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
MusicArtistDto expectedArtist = _musicArtistDtoFixture.Create();
|
||||
expectedArtist.Metadata!.Name = "An artist";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{expectedArtist.LibraryId}/artists/{expectedArtist.Id}", expectedArtist);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/audio-library/music-library/artists/{expectedArtist.Id}?libraryId={expectedArtist.LibraryId}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType);
|
||||
Assert.Contains("An artist", content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EditMusicArtist_WhenNotAuthenticated_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.GetAsync($"/en-us/library/audio-library/music-library/artists/{Guid.NewGuid()}?libraryId={Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("libraries/", StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
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.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetMusicArtist;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetMusicArtistEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetMusicArtistEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly MusicArtistDtoFixture _musicArtistDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetMusicArtistEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetMusicArtistEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMusicArtist_WhenCalledByAuthenticatedUser_ShouldReturnArtistFromApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
MusicArtistDto expectedArtist = _musicArtistDtoFixture.Create(id: artistId, libraryId: libraryId);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/artists/{artistId}", expectedArtist);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/audio-library/music-library/artists/{artistId}/api-get-artist?libraryId={libraryId}");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(artistId, json.RootElement.GetProperty("data").GetProperty("id").GetGuid());
|
||||
Assert.Contains($"libraries/{libraryId}/artists/{artistId}", _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMusicArtist_WhenNotAuthenticated_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.GetAsync($"/en-us/library/audio-library/music-library/artists/{Guid.NewGuid()}/api-get-artist?libraryId={Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("libraries/", StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
}
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
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.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetMusicArtists;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetMusicArtistsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetMusicArtistsEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly PaginatedDtoFixture<MusicArtistLiteDto> _paginatedMusicArtistLiteDtoFixture = new();
|
||||
private readonly MusicArtistLiteDtoFixture _musicArtistLiteDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetMusicArtistsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetMusicArtistsEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMusicArtists_WhenCalledByAuthenticatedUser_ShouldReturnArtistsFromApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
const string EXPECTED_ENDPOINT = "libraries/{0}/artists/lite?currentPage=1&perPage=20&shouldIgnoreThePrefixForAlphaPicker=False";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(
|
||||
string.Format(EXPECTED_ENDPOINT, libraryId),
|
||||
_paginatedMusicArtistLiteDtoFixture.Create(data: [_musicArtistLiteDtoFixture.Create(name: "Test Artist")], currentPage: 1, perPage: 20, count: 1, numberOfPages: 1));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/audio-library/music-library/artists/api-get-artists?libraryId={libraryId}¤tPage=1&perPage=20&shouldIgnoreThePrefixForAlphaPicker=false");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(1, json.RootElement.GetProperty("data").GetProperty("currentPage").GetInt32());
|
||||
Assert.Contains(string.Format(EXPECTED_ENDPOINT, libraryId), _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMusicArtists_WhenNotAuthenticated_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.GetAsync($"/en-us/library/audio-library/music-library/artists/api-get-artists?libraryId={Guid.NewGuid()}&shouldIgnoreThePrefixForAlphaPicker=false");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("libraries/", StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.Index;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.Index;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="MusicArtistsIndexViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicArtistsIndexViewEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly LibraryDtoFixture _libraryDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MusicArtistsIndexViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public MusicArtistsIndexViewEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MusicArtistsIndex_WhenCalledByAuthenticatedUserWithLibraryId_ShouldRenderArtistsPage()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
LibraryDto expectedLibrary = _libraryDtoFixture.Create(id: libraryId, title: "Music");
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}", expectedLibrary);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/audio-library/music-library/artists?libraryId={libraryId}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType);
|
||||
Assert.Contains("search-input", content);
|
||||
Assert.Contains($"libraries/{libraryId}", _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MusicArtistsIndex_WhenCalledByAuthenticatedUserWithoutLibraryId_ShouldRedirectToHome()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/library/audio-library/music-library/artists");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Contains("/en-us", response.Headers.Location!.ToString());
|
||||
}
|
||||
}
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.RestoreMusicArtist;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.RestoreMusicArtist;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="RestoreMusicArtistEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RestoreMusicArtistEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RestoreMusicArtistEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public RestoreMusicArtistEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RestoreMusicArtist_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldForwardPostAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
_apiFactory.ApiClientStub.RegisterPostSuccess($"libraries/{libraryId}/artists/{artistId}/restore");
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage restoreRequest = CreateRestoreRequest(artistId, libraryId);
|
||||
restoreRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(restoreRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.True(json.RootElement.GetProperty("data").GetProperty("isRestored").GetBoolean());
|
||||
Assert.Contains($"libraries/{libraryId}/artists/{artistId}/restore", _apiFactory.ApiClientStub.PostRequests.Select(postRequest => postRequest.Endpoint));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RestoreMusicArtist_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpRequestMessage restoreRequest = CreateRestoreRequest(Guid.NewGuid(), Guid.NewGuid());
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(restoreRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Empty(_apiFactory.ApiClientStub.PostRequests);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RestoreMusicArtist_WhenNotAuthenticated_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
HttpRequestMessage restoreRequest = CreateRestoreRequest(Guid.NewGuid(), Guid.NewGuid());
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.SendAsync(restoreRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Empty(_apiFactory.ApiClientStub.PostRequests);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the restore request for the artist identified by the route, with the owning library passed through the query string.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The route Id of the artist to restore.</param>
|
||||
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
|
||||
/// <returns>The configured restore request.</returns>
|
||||
private static HttpRequestMessage CreateRestoreRequest(Guid artistId, Guid libraryId)
|
||||
{
|
||||
HttpRequestMessage restoreRequest = new(HttpMethod.Post, $"/en-us/library/audio-library/music-library/artists/{artistId}/api-restore-artist?libraryId={libraryId}")
|
||||
{
|
||||
// The front-end sends the JSON content type even for bodyless POST requests, which triggers the antiforgery validation.
|
||||
Content = new StringContent("{}", Encoding.UTF8, "application/json")
|
||||
};
|
||||
// The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted.
|
||||
restoreRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
restoreRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
return restoreRequest;
|
||||
}
|
||||
}
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Artists;
|
||||
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 Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.SaveMusicArtist;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="SaveMusicArtistEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SaveMusicArtistEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly UpdateMusicArtistRequestFixture _updateMusicArtistRequestFixture = new();
|
||||
private readonly MusicArtistDtoFixture _musicArtistDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SaveMusicArtistEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public SaveMusicArtistEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveMusicArtist_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldForwardUpdateAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
UpdateMusicArtistRequest request = _updateMusicArtistRequestFixture.Create();
|
||||
MusicArtistDto expectedArtist = _musicArtistDtoFixture.Create(id: artistId, libraryId: libraryId);
|
||||
_apiFactory.ApiClientStub.RegisterPutResponse($"libraries/{libraryId}/artists/{artistId}", expectedArtist);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage saveRequest = CreateSaveRequest(artistId, libraryId, request);
|
||||
saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(artistId, json.RootElement.GetProperty("data").GetProperty("id").GetGuid());
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/artists/{artistId}" && putRequest.Data is UpdateMusicArtistRequest forwarded && forwarded.Metadata!.Name == request.Metadata!.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveMusicArtist_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
UpdateMusicArtistRequest request = _updateMusicArtistRequestFixture.Create();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage saveRequest = CreateSaveRequest(artistId, libraryId, request);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/artists/{artistId}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveMusicArtist_WhenNotAuthenticated_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
HttpRequestMessage saveRequest = CreateSaveRequest(Guid.NewGuid(), Guid.NewGuid(), _updateMusicArtistRequestFixture.Create());
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.SendAsync(saveRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Empty(_apiFactory.ApiClientStub.PutRequests);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the save request that PUTs the given <paramref name="request"/> to the artist identified by the route,
|
||||
/// with the owning library passed through the query string.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The route Id of the artist to save.</param>
|
||||
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
|
||||
/// <param name="request">The artist data to send.</param>
|
||||
/// <returns>The configured save request.</returns>
|
||||
private static HttpRequestMessage CreateSaveRequest(Guid artistId, Guid libraryId, UpdateMusicArtistRequest request)
|
||||
{
|
||||
HttpRequestMessage saveRequest = new(HttpMethod.Put, $"/en-us/library/audio-library/music-library/artists/{artistId}/api-save-artist?libraryId={libraryId}")
|
||||
{
|
||||
Content = JsonContent.Create(request)
|
||||
};
|
||||
saveRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
saveRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
return saveRequest;
|
||||
}
|
||||
}
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
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 Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.UpdateArtistCover;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="UpdateArtistCoverEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateArtistCoverEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly UpdateMusicCoverDtoFixture _updateMusicCoverDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateArtistCoverEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public UpdateArtistCoverEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateArtistCover_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldUploadCoverAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
const string EXPECTED_PATH = "/media/artists/cover.png";
|
||||
_apiFactory.ApiClientStub.RegisterPutResponse($"libraries/{libraryId}/artists/{artistId}/cover", _updateMusicCoverDtoFixture.Create(coverPath: EXPECTED_PATH));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage uploadRequest = CreateUploadRequest(artistId, libraryId, "cover.png");
|
||||
uploadRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(uploadRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(EXPECTED_PATH, json.RootElement.GetProperty("data").GetString());
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/artists/{artistId}/cover" && putRequest.Data as string == "cover.png");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateArtistCover_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage uploadRequest = CreateUploadRequest(artistId, libraryId, "cover.png");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(uploadRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/artists/{artistId}/cover");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateArtistCover_WhenCalledWithoutUploadedFile_ShouldForwardRequestAndReturnFailure()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
_apiFactory.ApiClientStub.RegisterPutResponse($"libraries/{libraryId}/artists/{artistId}/cover", _updateMusicCoverDtoFixture.Create(includeCoverPath: false));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
MultipartFormDataContent noFileForm = [];
|
||||
noFileForm.Add(new StringContent("unrelated-field"));
|
||||
HttpRequestMessage uploadRequest = new(HttpMethod.Put, $"/en-us/library/audio-library/music-library/artists/{artistId}/api-update-cover?libraryId={libraryId}")
|
||||
{
|
||||
Content = noFileForm
|
||||
};
|
||||
uploadRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
uploadRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(uploadRequest);
|
||||
|
||||
// Assert
|
||||
// The web does not short-circuit the missing file; it forwards the request without a file, so that the upstream API reports it.
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/artists/{artistId}/cover" && putRequest.Data == null);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateArtistCover_WhenNotAuthenticated_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
HttpRequestMessage uploadRequest = CreateUploadRequest(Guid.NewGuid(), Guid.NewGuid(), "cover.png");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.SendAsync(uploadRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Empty(_apiFactory.ApiClientStub.PutRequests);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the multipart PUT request that uploads a cover to the artist identified by the route.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The route Id of the artist whose cover is uploaded.</param>
|
||||
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
|
||||
/// <param name="fileName">The name of the uploaded file.</param>
|
||||
/// <returns>The configured upload request.</returns>
|
||||
private static HttpRequestMessage CreateUploadRequest(Guid artistId, Guid libraryId, string fileName)
|
||||
{
|
||||
MultipartFormDataContent form = [];
|
||||
ByteArrayContent fileContent = new(Encoding.UTF8.GetBytes("fake cover payload"));
|
||||
fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
|
||||
form.Add(fileContent, "cover", fileName);
|
||||
return new HttpRequestMessage(HttpMethod.Put, $"/en-us/library/audio-library/music-library/artists/{artistId}/api-update-cover?libraryId={libraryId}")
|
||||
{
|
||||
Content = form
|
||||
};
|
||||
}
|
||||
}
|
||||
+148
@@ -0,0 +1,148 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.DeletedMusicItems;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.DeletedMusicItems;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="DeletedMusicItemsViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeletedMusicItemsViewEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly LibraryDtoFixture _libraryDtoFixture = new();
|
||||
private readonly DeletedMusicArtistDtoFixture _deletedMusicArtistDtoFixture = new();
|
||||
private readonly DeletedMusicAlbumDtoFixture _deletedMusicAlbumDtoFixture = new();
|
||||
private readonly DeletedMusicTrackDtoFixture _deletedMusicTrackDtoFixture = new();
|
||||
private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeletedMusicItemsViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public DeletedMusicItemsViewEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeletedMusicItemsView_WhenCalledByAuthenticatedUserWithLibraryId_ShouldRenderDeletedMusicItemsPage()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
LibraryDto library = _libraryDtoFixture.Create(id: libraryId, title: "Music");
|
||||
DeletedMusicArtistDto deletedArtist = _deletedMusicArtistDtoFixture.Create(libraryId: libraryId, id: artistId, name: "Deleted Artist");
|
||||
DeletedMusicAlbumDto deletedAlbum = _deletedMusicAlbumDtoFixture.Create(libraryId: libraryId, id: albumId, artistId: artistId, artistName: "Deleted Artist", title: "Deleted Album");
|
||||
DeletedMusicTrackDto deletedTrack = _deletedMusicTrackDtoFixture.Create(libraryId: libraryId, artistId: artistId, artistName: "Deleted Artist", albumId: albumId, albumTitle: "Deleted Album", title: "Deleted Track");
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}", library);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/artists/deleted-items", new[] { deletedArtist });
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/albums/deleted-items", new[] { deletedAlbum });
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/tracks/deleted-items", new[] { deletedTrack });
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/audio-library/music-library/deleted-items?libraryId={libraryId}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType);
|
||||
Assert.Contains("deleted-artists-table", content);
|
||||
Assert.Contains("deleted-albums-table", content);
|
||||
Assert.Contains("deleted-tracks-table", content);
|
||||
Assert.Contains("btn-restore-artist", content);
|
||||
Assert.Contains("btn-restore-album", content);
|
||||
Assert.Contains("btn-restore-track", content);
|
||||
Assert.Contains("Deleted Artist", content);
|
||||
Assert.Contains("Deleted Album", content);
|
||||
Assert.Contains("Deleted Track", content);
|
||||
Assert.Contains($"libraries/{libraryId}", _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
Assert.Contains($"libraries/{libraryId}/artists/deleted-items", _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
Assert.Contains($"libraries/{libraryId}/albums/deleted-items", _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
Assert.Contains($"libraries/{libraryId}/tracks/deleted-items", _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeletedMusicItemsView_WhenDeletedItemNamesContainMarkup_ShouldEncodeThem()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
LibraryDto library = _libraryDtoFixture.Create(id: libraryId, title: "Music");
|
||||
DeletedMusicArtistDto deletedArtist = _deletedMusicArtistDtoFixture.Create(libraryId: libraryId, name: "<script>alert('x')</script>");
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}", library);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/artists/deleted-items", new[] { deletedArtist });
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/albums/deleted-items", Array.Empty<DeletedMusicAlbumDto>());
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/tracks/deleted-items", Array.Empty<DeletedMusicTrackDto>());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/audio-library/music-library/deleted-items?libraryId={libraryId}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Contains("<script>alert", content);
|
||||
Assert.DoesNotContain("<script>alert('x')</script>", content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeletedMusicItemsView_WhenTheApiReturnsForbidden_ShouldRedirectWithoutLeakingDetails()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
LibraryDto library = _libraryDtoFixture.Create(id: libraryId, title: "Music");
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}", library);
|
||||
string endpoint = $"libraries/{libraryId}/artists/deleted-items";
|
||||
_apiFactory.ApiClientStub.RegisterGetException(endpoint, new ApiException(
|
||||
_problemDetailsDtoFixture.Create(title: "General.Unauthorized", detail: "NotAuthorized"),
|
||||
HttpStatusCode.Forbidden,
|
||||
endpoint));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/audio-library/music-library/deleted-items?libraryId={libraryId}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
// A browser navigation that the API forbids is redirected to the access denied page, without rendering any of the forbidden data.
|
||||
Assert.Equal(HttpStatusCode.Found, response.StatusCode);
|
||||
Assert.NotNull(response.Headers.Location);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeletedMusicItemsView_WhenCalledWithoutLibraryId_ShouldRedirectToHome()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/library/audio-library/music-library/deleted-items");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Contains("/en-us", response.Headers.Location!.ToString());
|
||||
}
|
||||
}
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.DeleteMusicTrack;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.DeleteMusicTrack;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="DeleteMusicTrackEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteMusicTrackEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteMusicTrackEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public DeleteMusicTrackEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteMusicTrack_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldForwardDeleteAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
_apiFactory.ApiClientStub.RegisterDeleteSuccess($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}");
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(artistId, albumId, trackId, libraryId);
|
||||
deleteRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Contains($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}", _apiFactory.ApiClientStub.DeleteEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteMusicTrack_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(artistId, albumId, trackId, libraryId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.DoesNotContain($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}", _apiFactory.ApiClientStub.DeleteEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteMusicTrack_WhenNotAuthenticated_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid());
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.SendAsync(deleteRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Empty(_apiFactory.ApiClientStub.DeleteEndpointsCalled);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the delete request for the track identified by the route, with the owning library passed through the query string.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The route Id of the artist the track belongs to.</param>
|
||||
/// <param name="albumId">The route Id of the album the track belongs to.</param>
|
||||
/// <param name="trackId">The route Id of the track to delete.</param>
|
||||
/// <param name="libraryId">The Id of the media library the track belongs to.</param>
|
||||
/// <returns>The configured delete request.</returns>
|
||||
private static HttpRequestMessage CreateDeleteRequest(Guid artistId, Guid albumId, Guid trackId, Guid libraryId)
|
||||
{
|
||||
HttpRequestMessage deleteRequest = new(HttpMethod.Delete, $"/en-us/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-delete-track?libraryId={libraryId}")
|
||||
{
|
||||
// The front-end sends the JSON content type even for DELETE requests, which triggers the antiforgery validation.
|
||||
Content = new StringContent("{}", Encoding.UTF8, "application/json")
|
||||
};
|
||||
// The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted.
|
||||
deleteRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
deleteRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
return deleteRequest;
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.EditMusicTrack;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.EditMusicTrack;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="EditMusicTrackViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class EditMusicTrackViewEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly MusicTrackDtoFixture _musicTrackDtoFixture = new();
|
||||
private readonly MusicAlbumDtoFixture _musicAlbumDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="EditMusicTrackViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public EditMusicTrackViewEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EditMusicTrack_WhenCalledByAuthenticatedUser_ShouldRenderEditTrackPage()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
MusicTrackDto expectedTrack = _musicTrackDtoFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId);
|
||||
expectedTrack.Metadata!.Title = "A track";
|
||||
MusicAlbumDto expectedAlbum = _musicAlbumDtoFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}", expectedTrack);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}", expectedAlbum);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}?libraryId={libraryId}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType);
|
||||
Assert.Contains("A track", content);
|
||||
Assert.Contains($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}", _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
Assert.Contains($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}", _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EditMusicTrack_WhenNotAuthenticated_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.GetAsync($"/en-us/library/audio-library/music-library/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}?libraryId={Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("libraries/", StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
}
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
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.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetAlbumTracks;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetAlbumTracksEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetAlbumTracksEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly PaginatedDtoFixture<MusicTrackLiteDto> _paginatedMusicTrackLiteDtoFixture = new();
|
||||
private readonly MusicTrackLiteDtoFixture _musicTrackLiteDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetAlbumTracksEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetAlbumTracksEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbumTracks_WhenCalledByAuthenticatedUser_ShouldReturnTracksFromApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
PaginatedDto<MusicTrackLiteDto> expectedResponse = _paginatedMusicTrackLiteDtoFixture.Create(data: [_musicTrackLiteDtoFixture.Create(title: "Test Track")]);
|
||||
string expectedEndpoint = $"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/lite?currentPage=1&perPage=20";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, expectedResponse);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/api-get-tracks?libraryId={libraryId}¤tPage=1&perPage=20");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(expectedResponse.Data.Count, json.RootElement.GetProperty("data").GetProperty("data").GetArrayLength());
|
||||
Assert.Contains(expectedEndpoint, _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbumTracks_WhenNotAuthenticated_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.GetAsync($"/en-us/library/audio-library/music-library/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/api-get-tracks?libraryId={Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("libraries/", StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
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.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetMusicTrack;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetMusicTrackEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetMusicTrackEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly MusicTrackDtoFixture _musicTrackDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetMusicTrackEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetMusicTrackEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMusicTrack_WhenCalledByAuthenticatedUser_ShouldReturnTrackFromApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
MusicTrackDto expectedTrack = _musicTrackDtoFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}", expectedTrack);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-get-track?libraryId={libraryId}");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(trackId, json.RootElement.GetProperty("data").GetProperty("id").GetGuid());
|
||||
Assert.Contains($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}", _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMusicTrack_WhenNotAuthenticated_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.GetAsync($"/en-us/library/audio-library/music-library/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/api-get-track?libraryId={Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("libraries/", StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
}
|
||||
+194
@@ -0,0 +1,194 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetPlaybackManifest;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetPlaybackManifest;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetPlaybackManifestEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetPlaybackManifestEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private const string VALID_DELIVERY_ID = "0123456789abcdef0123456789abcdef";
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly PlaybackManifestDtoFixture _playbackManifestDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPlaybackManifestEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetPlaybackManifestEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaybackManifest_WhenManifestIsNotADirectPlay_ShouldReturnTheWebProxyPaths()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
PlaybackManifestDto manifest = _playbackManifestDtoFixture.Create(
|
||||
trackId: trackId,
|
||||
isDirectPlay: false,
|
||||
deliveryId: VALID_DELIVERY_ID,
|
||||
segmentStreamPathTemplate: "/api/v1/libraries/ancient/stream/deliveries/{deliveryId}/segments/{segmentIndex}");
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/playback-manifest", manifest);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = CreateGetRequest(libraryId, artistId, albumId, trackId);
|
||||
string expectedStreamPath = $"/en-us/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-stream-track?libraryId={libraryId}";
|
||||
string expectedSegmentStreamPathTemplate = $"/en-us/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-stream-track-segment/{{deliveryId}}/{{segmentIndex}}?libraryId={libraryId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
JsonElement data = json.RootElement.GetProperty("data");
|
||||
Assert.Equal(expectedStreamPath, data.GetProperty("streamPath").GetString());
|
||||
Assert.Equal(expectedSegmentStreamPathTemplate, data.GetProperty("segmentStreamPathTemplate").GetString());
|
||||
Assert.Equal(VALID_DELIVERY_ID, data.GetProperty("deliveryId").GetString());
|
||||
Assert.DoesNotContain("http", data.GetProperty("streamPath").GetString(), StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("http", data.GetProperty("segmentStreamPathTemplate").GetString(), StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Contains("private", response.Headers.CacheControl?.ToString());
|
||||
Assert.Contains("no-store", response.Headers.CacheControl?.ToString());
|
||||
Assert.Contains("Cookie", response.Headers.Vary);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaybackManifest_WhenManifestIsADirectPlay_ShouldReturnNullDeliveryAndTemplate()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
PlaybackManifestDto manifest = _playbackManifestDtoFixture.Create(
|
||||
trackId: trackId,
|
||||
isDirectPlay: true,
|
||||
includeDeliveryId: false,
|
||||
includeSegmentStreamPathTemplate: false);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/playback-manifest", manifest);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = CreateGetRequest(libraryId, artistId, albumId, trackId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
JsonElement data = json.RootElement.GetProperty("data");
|
||||
Assert.Equal(JsonValueKind.Null, data.GetProperty("deliveryId").ValueKind);
|
||||
Assert.Equal(JsonValueKind.Null, data.GetProperty("segmentStreamPathTemplate").ValueKind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaybackManifest_WhenApiDeclaresATemplateWithAnInvalidDeliveryId_ShouldReturnBadGateway()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
PlaybackManifestDto manifest = _playbackManifestDtoFixture.Create(
|
||||
trackId: trackId,
|
||||
isDirectPlay: false,
|
||||
deliveryId: "not-a-valid-handle",
|
||||
segmentStreamPathTemplate: "/api/v1/libraries/ancient/stream/deliveries/{deliveryId}/segments/{segmentIndex}");
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/playback-manifest", manifest);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = CreateGetRequest(libraryId, artistId, albumId, trackId);
|
||||
// The player fetch classifies as a raw media request, which is answered with a bare status instead of a page or a JSON body.
|
||||
getRequest.Headers.Accept.Clear();
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("audio/mpeg"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadGateway, response.StatusCode);
|
||||
Assert.Equal(string.Empty, content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaybackManifest_WhenNotAuthenticated_ShouldRedirectToLoginWithoutCallingTheApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.GetAsync($"/en-us/library/audio-library/music-library/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/api-get-playback-manifest?libraryId={Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("libraries/", StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Tracks; --")] // Destructive injection.
|
||||
[InlineData("' OR '1'='1")] // Boolean-based injection.
|
||||
public async Task GetPlaybackManifest_WithSQLInjectionInRouteId_ShouldNormalizeTheIdWithoutLeakingData(string maliciousId)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
string normalizedId = Guid.Empty.ToString();
|
||||
PlaybackManifestDto manifest = _playbackManifestDtoFixture.Create(isDirectPlay: true, includeDeliveryId: false, includeSegmentStreamPathTemplate: false);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/artists/{normalizedId}/albums/{normalizedId}/tracks/{normalizedId}/playback-manifest", manifest);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/audio-library/music-library/artists/{Uri.EscapeDataString(maliciousId)}/albums/{Uri.EscapeDataString(maliciousId)}/tracks/{Uri.EscapeDataString(maliciousId)}/api-get-playback-manifest?libraryId={libraryId}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using (JsonDocument json = JsonDocument.Parse(content))
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(maliciousId, content, StringComparison.Ordinal);
|
||||
Assert.Contains(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == $"libraries/{libraryId}/artists/{normalizedId}/albums/{normalizedId}/tracks/{normalizedId}/playback-manifest");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an authenticated JSON request for the playback manifest of a track.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the track belongs to.</param>
|
||||
/// <param name="artistId">The Id of the artist the album belongs to.</param>
|
||||
/// <param name="albumId">The Id of the album the track belongs to.</param>
|
||||
/// <param name="trackId">The Id of the track.</param>
|
||||
/// <returns>The configured request.</returns>
|
||||
private static HttpRequestMessage CreateGetRequest(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)
|
||||
{
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-get-playback-manifest?libraryId={libraryId}");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
return getRequest;
|
||||
}
|
||||
}
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.RestoreMusicTrack;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.RestoreMusicTrack;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="RestoreMusicTrackEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RestoreMusicTrackEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RestoreMusicTrackEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public RestoreMusicTrackEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RestoreMusicTrack_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldForwardPostAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
_apiFactory.ApiClientStub.RegisterPostSuccess($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/restore");
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage restoreRequest = CreateRestoreRequest(artistId, albumId, trackId, libraryId);
|
||||
restoreRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(restoreRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.True(json.RootElement.GetProperty("data").GetProperty("isRestored").GetBoolean());
|
||||
Assert.Contains($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/restore", _apiFactory.ApiClientStub.PostRequests.Select(postRequest => postRequest.Endpoint));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RestoreMusicTrack_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpRequestMessage restoreRequest = CreateRestoreRequest(Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid());
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(restoreRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Empty(_apiFactory.ApiClientStub.PostRequests);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RestoreMusicTrack_WhenNotAuthenticated_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
HttpRequestMessage restoreRequest = CreateRestoreRequest(Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid());
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.SendAsync(restoreRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Empty(_apiFactory.ApiClientStub.PostRequests);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the restore request for the track identified by the route, with the owning library passed through the query string.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The route Id of the artist the track belongs to.</param>
|
||||
/// <param name="albumId">The route Id of the album the track belongs to.</param>
|
||||
/// <param name="trackId">The route Id of the track to restore.</param>
|
||||
/// <param name="libraryId">The Id of the media library the track belongs to.</param>
|
||||
/// <returns>The configured restore request.</returns>
|
||||
private static HttpRequestMessage CreateRestoreRequest(Guid artistId, Guid albumId, Guid trackId, Guid libraryId)
|
||||
{
|
||||
HttpRequestMessage restoreRequest = new(HttpMethod.Post, $"/en-us/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-restore-track?libraryId={libraryId}")
|
||||
{
|
||||
// The front-end sends the JSON content type even for bodyless POST requests, which triggers the antiforgery validation.
|
||||
Content = new StringContent("{}", Encoding.UTF8, "application/json")
|
||||
};
|
||||
// The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted.
|
||||
restoreRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
restoreRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
return restoreRequest;
|
||||
}
|
||||
}
|
||||
+194
@@ -0,0 +1,194 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
|
||||
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 Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.SaveMusicTrack;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="SaveMusicTrackEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SaveMusicTrackEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private static readonly JsonSerializerOptions s_jsonOptions = new(JsonSerializerDefaults.Web)
|
||||
{
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly UpdateMusicTrackRequestFixture _updateMusicTrackRequestFixture = new();
|
||||
private readonly MusicTrackDtoFixture _musicTrackDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SaveMusicTrackEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public SaveMusicTrackEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveMusicTrack_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldForwardUpdateAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
UpdateMusicTrackRequest request = _updateMusicTrackRequestFixture.Create();
|
||||
MusicTrackDto expectedTrack = _musicTrackDtoFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId);
|
||||
_apiFactory.ApiClientStub.RegisterPutResponse($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}", expectedTrack);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage saveRequest = CreateSaveRequest(artistId, albumId, trackId, libraryId, request);
|
||||
saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(trackId, json.RootElement.GetProperty("data").GetProperty("id").GetGuid());
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}" && putRequest.Data is UpdateMusicTrackRequest forwarded && forwarded.Metadata!.Title == request.Metadata!.Title);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveMusicTrack_WhenPostedBodyCarriesAFilePath_ShouldNotForwardAFilePathToTheApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
string attemptedPath = Path.Combine(Path.GetTempPath(), "lumina-outside-content-root", "etc", "hosts");
|
||||
UpdateMusicTrackRequest request = _updateMusicTrackRequestFixture.Create();
|
||||
MusicTrackDto expectedTrack = _musicTrackDtoFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId);
|
||||
_apiFactory.ApiClientStub.RegisterPutResponse($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}", expectedTrack);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage saveRequest = CreateSaveRequest(artistId, albumId, trackId, libraryId, request, attemptedPath);
|
||||
saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
(string Endpoint, object? Data) forwardedRequest = Assert.Single(
|
||||
_apiFactory.ApiClientStub.PutRequests,
|
||||
putRequest => putRequest.Endpoint == $"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}");
|
||||
UpdateMusicTrackRequest forwarded = Assert.IsType<UpdateMusicTrackRequest>(forwardedRequest.Data);
|
||||
Assert.Equal(request.Metadata!.Title, forwarded.Metadata!.Title);
|
||||
// The Web request type has no file system path, so the posted path is dropped before the API call.
|
||||
using JsonDocument forwardedJson = JsonDocument.Parse(JsonSerializer.Serialize(forwarded, s_jsonOptions));
|
||||
Assert.False(forwardedJson.RootElement.TryGetProperty("path", out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveMusicTrack_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
UpdateMusicTrackRequest request = _updateMusicTrackRequestFixture.Create();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage saveRequest = CreateSaveRequest(artistId, albumId, trackId, libraryId, request);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveMusicTrack_WhenNotAuthenticated_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
HttpRequestMessage saveRequest = CreateSaveRequest(Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), _updateMusicTrackRequestFixture.Create());
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.SendAsync(saveRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Empty(_apiFactory.ApiClientStub.PutRequests);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the save request that PUTs the given <paramref name="request"/> to the track identified by the route,
|
||||
/// with the owning library passed through the query string.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The route Id of the artist the track belongs to.</param>
|
||||
/// <param name="albumId">The route Id of the album the track belongs to.</param>
|
||||
/// <param name="trackId">The route Id of the track to save.</param>
|
||||
/// <param name="libraryId">The Id of the media library the track belongs to.</param>
|
||||
/// <param name="request">The track data to send.</param>
|
||||
/// <returns>The configured save request.</returns>
|
||||
private static HttpRequestMessage CreateSaveRequest(Guid artistId, Guid albumId, Guid trackId, Guid libraryId, UpdateMusicTrackRequest request)
|
||||
{
|
||||
HttpRequestMessage saveRequest = new(HttpMethod.Put, $"/en-us/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-save-track?libraryId={libraryId}")
|
||||
{
|
||||
Content = JsonContent.Create(request)
|
||||
};
|
||||
saveRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
saveRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
return saveRequest;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the save request that PUTs the given <paramref name="request"/>, carrying an extra file system path property,
|
||||
/// to the track identified by the route, with the owning library passed through the query string.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The route Id of the artist the track belongs to.</param>
|
||||
/// <param name="albumId">The route Id of the album the track belongs to.</param>
|
||||
/// <param name="trackId">The route Id of the track to save.</param>
|
||||
/// <param name="libraryId">The Id of the media library the track belongs to.</param>
|
||||
/// <param name="request">The track data to send.</param>
|
||||
/// <param name="attemptedPath">The file system path to inject into the posted body.</param>
|
||||
/// <returns>The configured save request.</returns>
|
||||
private static HttpRequestMessage CreateSaveRequest(Guid artistId, Guid albumId, Guid trackId, Guid libraryId, UpdateMusicTrackRequest request, string attemptedPath)
|
||||
{
|
||||
JsonObject body = JsonSerializer.SerializeToNode(request, s_jsonOptions)!.AsObject();
|
||||
body["path"] = attemptedPath;
|
||||
HttpRequestMessage saveRequest = new(HttpMethod.Put, $"/en-us/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-save-track?libraryId={libraryId}")
|
||||
{
|
||||
Content = new StringContent(body.ToJsonString(s_jsonOptions), Encoding.UTF8, "application/json")
|
||||
};
|
||||
saveRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
saveRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
return saveRequest;
|
||||
}
|
||||
}
|
||||
+202
@@ -0,0 +1,202 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
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 Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.ShuffleTracks;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="ShuffleTracksEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ShuffleTracksEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private const string SHUFFLE_TRACKS_PATH = "/en-us/library/audio-library/music-library/tracks/api-shuffle-tracks";
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly ShuffleTracksRequestFixture _shuffleTracksRequestFixture = new();
|
||||
private readonly MusicShuffleTrackDtoFixture _musicShuffleTrackDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ShuffleTracksEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public ShuffleTracksEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ShuffleTracks_WhenApiReturnsTracks_ShouldReturnTheMappedTracks()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid excludedTrackId = Guid.NewGuid();
|
||||
ShuffleTracksRequest request = _shuffleTracksRequestFixture.Create(
|
||||
count: 25, excludedTrackIds: [excludedTrackId]);
|
||||
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");
|
||||
_apiFactory.ApiClientStub.RegisterPostResponse(ExpectedEndpoint(request.LibraryId), new List<MusicShuffleTrackDto> { expectedTrack });
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(CreateShuffleRequest(request));
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
JsonElement data = json.RootElement.GetProperty("data");
|
||||
Assert.Equal(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());
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ShuffleTracks_WhenCalled_ShouldForwardTheRequestToTheLibraryShuffleEndpoint()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid firstExcludedTrackId = Guid.NewGuid();
|
||||
Guid secondExcludedTrackId = Guid.NewGuid();
|
||||
ShuffleTracksRequest request = _shuffleTracksRequestFixture.Create(
|
||||
count: 25,
|
||||
artistId: artistId,
|
||||
albumId: albumId,
|
||||
excludedTrackIds: [firstExcludedTrackId, secondExcludedTrackId]);
|
||||
_apiFactory.ApiClientStub.RegisterPostResponse(ExpectedEndpoint(request.LibraryId), new List<MusicShuffleTrackDto>());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(CreateShuffleRequest(request));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
(string Endpoint, object? Data) forwardedRequest = Assert.Single(
|
||||
_apiFactory.ApiClientStub.PostRequests,
|
||||
postRequest => postRequest.Endpoint == ExpectedEndpoint(request.LibraryId));
|
||||
Assert.Equal($"libraries/{request.LibraryId}/tracks/shuffle", forwardedRequest.Endpoint);
|
||||
ShuffleTracksRequest forwarded = Assert.IsType<ShuffleTracksRequest>(forwardedRequest.Data);
|
||||
Assert.Equal(request.LibraryId, forwarded.LibraryId);
|
||||
Assert.Equal(25, forwarded.Count);
|
||||
Assert.Equal(artistId, forwarded.ArtistId);
|
||||
Assert.Equal(albumId, forwarded.AlbumId);
|
||||
Assert.NotNull(forwarded.ExcludedTrackIds);
|
||||
Assert.Equal(new[] { firstExcludedTrackId, secondExcludedTrackId }, forwarded.ExcludedTrackIds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ShuffleTracks_WhenApiReturnsNoTracks_ShouldReturnAnEmptyDataArray()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
ShuffleTracksRequest request = _shuffleTracksRequestFixture.Create();
|
||||
_apiFactory.ApiClientStub.RegisterPostResponse(ExpectedEndpoint(request.LibraryId), new List<MusicShuffleTrackDto>());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(CreateShuffleRequest(request));
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
JsonElement data = json.RootElement.GetProperty("data");
|
||||
Assert.Equal(JsonValueKind.Array, data.ValueKind);
|
||||
Assert.Equal(0, data.GetArrayLength());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ShuffleTracks_WhenBodyIsMalformed_ShouldNotLeakServerDetailsOrCallTheApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
StringContent body = new("{\"libraryId\": \"'; DROP TABLE Tracks; --\", \"count\": \"'; DROP TABLE Tracks; --\"}", Encoding.UTF8, "application/json");
|
||||
HttpRequestMessage shuffleRequest = new(HttpMethod.Post, SHUFFLE_TRACKS_PATH)
|
||||
{
|
||||
Content = body
|
||||
};
|
||||
shuffleRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
shuffleRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(shuffleRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
// The unbound request is rejected before the upstream API is reached, and the JSON error is sanitized.
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint.EndsWith("/tracks/shuffle", StringComparison.Ordinal));
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("'; DROP TABLE Tracks; --", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the upstream API endpoint of the shuffle request for the library identified by <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the tracks are sampled from.</param>
|
||||
/// <returns>The upstream endpoint.</returns>
|
||||
private static string ExpectedEndpoint(Guid libraryId)
|
||||
{
|
||||
return ApiRoutes.Music.SHUFFLE_TRACKS.Replace("{libraryId}", libraryId.ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the Web shuffle request that posts the given <paramref name="request"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The shuffle request to send.</param>
|
||||
/// <returns>The configured Web request.</returns>
|
||||
private static HttpRequestMessage CreateShuffleRequest(ShuffleTracksRequest request)
|
||||
{
|
||||
HttpRequestMessage shuffleRequest = new(HttpMethod.Post, SHUFFLE_TRACKS_PATH)
|
||||
{
|
||||
Content = JsonContent.Create(request)
|
||||
};
|
||||
shuffleRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
shuffleRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
return shuffleRequest;
|
||||
}
|
||||
}
|
||||
+237
@@ -0,0 +1,237 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.StreamMusicTrack;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.StreamMusicTrack;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="StreamMusicTrackEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class StreamMusicTrackEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="StreamMusicTrackEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public StreamMusicTrackEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StreamMusicTrack_WhenRequestIsValid_ShouldProxyTheApiStream()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.StreamingApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
string expectedEndpoint = BuildExpectedEndpoint(libraryId, artistId, albumId, trackId);
|
||||
byte[] contentBytes = CreateBytes(2048);
|
||||
_apiFactory.StreamingApiClientStub.RegisterStreamResponse(expectedEndpoint, await CreateStreamResultAsync(HttpStatusCode.OK, contentBytes, "audio/mpeg"));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync(BuildBrowserPath(libraryId, artistId, albumId, trackId));
|
||||
byte[] responseBytes = await response.Content.ReadAsByteArrayAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal("audio/mpeg", response.Content.Headers.ContentType?.MediaType);
|
||||
Assert.Equal(contentBytes.Length, response.Content.Headers.ContentLength);
|
||||
Assert.Equal(contentBytes, responseBytes);
|
||||
Assert.Contains("private", response.Headers.CacheControl?.ToString());
|
||||
Assert.DoesNotContain("public", response.Headers.CacheControl?.ToString());
|
||||
Assert.Contains("Cookie", response.Headers.Vary);
|
||||
Assert.Single(_apiFactory.StreamingApiClientStub.GetEndpointsCalled);
|
||||
Assert.Equal(expectedEndpoint, _apiFactory.StreamingApiClientStub.GetEndpointsCalled[0]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StreamMusicTrack_WhenConditionalHeadersArePresent_ShouldForwardThemToTheApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.StreamingApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
string expectedEndpoint = BuildExpectedEndpoint(libraryId, artistId, albumId, trackId);
|
||||
_apiFactory.StreamingApiClientStub.RegisterStreamResponse(expectedEndpoint, await CreateStreamResultAsync(HttpStatusCode.PartialContent, CreateBytes(100), "audio/mpeg"));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
using HttpRequestMessage request = new(HttpMethod.Get, BuildBrowserPath(libraryId, artistId, albumId, trackId));
|
||||
request.Headers.Range = new RangeHeaderValue(100, 199);
|
||||
request.Headers.IfRange = new RangeConditionHeaderValue(new EntityTagHeaderValue("\"etag-value\""));
|
||||
request.Headers.IfNoneMatch.Add(new EntityTagHeaderValue("\"etag-value\""));
|
||||
request.Headers.IfModifiedSince = new DateTimeOffset(2015, 10, 21, 7, 28, 0, TimeSpan.Zero);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.PartialContent, response.StatusCode);
|
||||
Assert.Single(_apiFactory.StreamingApiClientStub.StreamRequests);
|
||||
IReadOnlyDictionary<string, string> forwardedHeaders = _apiFactory.StreamingApiClientStub.StreamRequests[0].Headers;
|
||||
Assert.Equal("bytes=100-199", forwardedHeaders["Range"]);
|
||||
Assert.Equal("\"etag-value\"", forwardedHeaders["If-Range"]);
|
||||
Assert.Equal("\"etag-value\"", forwardedHeaders["If-None-Match"]);
|
||||
Assert.Equal("Wed, 21 Oct 2015 07:28:00 GMT", forwardedHeaders["If-Modified-Since"]);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(HttpStatusCode.ServiceUnavailable)] // A busy normalization pipeline is a transient condition.
|
||||
[InlineData(HttpStatusCode.TooManyRequests)] // The stream concurrency limit was reached.
|
||||
public async Task StreamMusicTrack_WhenApiReportsATransientCondition_ShouldReturnABareStatus(HttpStatusCode statusCode)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.StreamingApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
string expectedEndpoint = BuildExpectedEndpoint(libraryId, artistId, albumId, trackId);
|
||||
_apiFactory.StreamingApiClientStub.RegisterStreamException(expectedEndpoint, new ApiException(
|
||||
new ProblemDetailsDto { Title = "General.Failure", Detail = "InternalServerError", Status = (int)statusCode },
|
||||
statusCode,
|
||||
expectedEndpoint));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
using HttpRequestMessage request = new(HttpMethod.Get, BuildBrowserPath(libraryId, artistId, albumId, trackId));
|
||||
// A media caller asks for audio, which is what makes the failure a bare status rather than a JSON or page response.
|
||||
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("audio/mpeg"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(request);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(statusCode, response.StatusCode);
|
||||
Assert.Equal(string.Empty, content);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(HttpStatusCode.ServiceUnavailable)] // A busy normalization pipeline is a transient condition.
|
||||
[InlineData(HttpStatusCode.TooManyRequests)] // The stream concurrency limit was reached.
|
||||
public async Task StreamMusicTrack_WhenApiReportsATransientConditionForANonMediaCaller_ShouldStillReturnABareStatus(HttpStatusCode statusCode)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.StreamingApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
string expectedEndpoint = BuildExpectedEndpoint(libraryId, artistId, albumId, trackId);
|
||||
_apiFactory.StreamingApiClientStub.RegisterStreamException(expectedEndpoint, new ApiException(
|
||||
new ProblemDetailsDto { Title = "General.Failure", Detail = "InternalServerError", Status = (int)statusCode },
|
||||
statusCode,
|
||||
expectedEndpoint));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
// No Accept and no Range header: a caller that is not asking for media must still receive the bare transient status, not a
|
||||
// JSON body with status 200 that the navigation error middleware would otherwise produce.
|
||||
using HttpRequestMessage request = new(HttpMethod.Get, BuildBrowserPath(libraryId, artistId, albumId, trackId));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(request);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(statusCode, response.StatusCode);
|
||||
Assert.Equal(string.Empty, content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StreamMusicTrack_WhenNotAuthenticated_ShouldRedirectToLoginWithoutCallingTheApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.StreamingApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.GetAsync(BuildBrowserPath(Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid()));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Empty(_apiFactory.StreamingApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the browser facing route of the direct stream of a track.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the track belongs to.</param>
|
||||
/// <param name="artistId">The Id of the artist the album belongs to.</param>
|
||||
/// <param name="albumId">The Id of the album the track belongs to.</param>
|
||||
/// <param name="trackId">The Id of the track.</param>
|
||||
/// <returns>The browser facing route of the requested stream.</returns>
|
||||
private static string BuildBrowserPath(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)
|
||||
{
|
||||
return $"/en-us/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-stream-track?libraryId={libraryId}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the upstream endpoint the stream request is expected to be sent to.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the track belongs to.</param>
|
||||
/// <param name="artistId">The Id of the artist the album belongs to.</param>
|
||||
/// <param name="albumId">The Id of the album the track belongs to.</param>
|
||||
/// <param name="trackId">The Id of the track.</param>
|
||||
/// <returns>The expected upstream endpoint.</returns>
|
||||
private static string BuildExpectedEndpoint(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)
|
||||
{
|
||||
return ApiRoutes.Music.STREAM_TRACK
|
||||
.Replace("{libraryId}", libraryId.ToString())
|
||||
.Replace("{artistId}", artistId.ToString())
|
||||
.Replace("{albumId}", albumId.ToString())
|
||||
.Replace("{trackId}", trackId.ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a streamed API response with a status code, a body and a 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 media type of the content.</param>
|
||||
/// <returns>The created streamed response.</returns>
|
||||
private static async Task<ApiStreamResult> CreateStreamResultAsync(HttpStatusCode statusCode, byte[] contentBytes, string contentType)
|
||||
{
|
||||
HttpResponseMessage response = new(statusCode)
|
||||
{
|
||||
Content = new ByteArrayContent(contentBytes)
|
||||
};
|
||||
response.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
|
||||
response.Headers.CacheControl = new CacheControlHeaderValue { Public = true, MaxAge = TimeSpan.FromSeconds(60) };
|
||||
return await ApiStreamResult.CreateAsync(response, CancellationToken.None);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a deterministic byte array that stands in for the content of a stream.
|
||||
/// </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))];
|
||||
}
|
||||
}
|
||||
+202
@@ -0,0 +1,202 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.StreamMusicTrackSegment;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.StreamMusicTrackSegment;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="StreamMusicTrackSegmentEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class StreamMusicTrackSegmentEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="StreamMusicTrackSegmentEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public StreamMusicTrackSegmentEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StreamMusicTrackSegment_WhenRequestIsValid_ShouldProxyTheApiSegment()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.StreamingApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
string deliveryId = Guid.NewGuid().ToString("N");
|
||||
const int SEGMENT_INDEX = 3;
|
||||
string expectedEndpoint = BuildExpectedEndpoint(libraryId, artistId, albumId, trackId, deliveryId, SEGMENT_INDEX);
|
||||
byte[] contentBytes = CreateBytes(1024);
|
||||
_apiFactory.StreamingApiClientStub.RegisterStreamResponse(expectedEndpoint, await CreateStreamResultAsync(contentBytes));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync(BuildBrowserPath(libraryId, artistId, albumId, trackId, deliveryId, SEGMENT_INDEX));
|
||||
byte[] responseBytes = await response.Content.ReadAsByteArrayAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.PartialContent, response.StatusCode);
|
||||
Assert.Equal("audio/mp4", response.Content.Headers.ContentType?.MediaType);
|
||||
Assert.Equal(contentBytes.Length, response.Content.Headers.ContentLength);
|
||||
Assert.Equal(contentBytes, responseBytes);
|
||||
Assert.Equal("9", response.Headers.GetValues(ApiStreamResult.SEGMENT_COUNT_HEADER_NAME).Single());
|
||||
Assert.Equal("6.5", response.Headers.GetValues(ApiStreamResult.SEGMENT_START_SECONDS_HEADER_NAME).Single());
|
||||
Assert.Equal("300", response.Headers.GetValues(ApiStreamResult.TRACK_DURATION_SECONDS_HEADER_NAME).Single());
|
||||
Assert.Contains("private", response.Headers.CacheControl?.ToString());
|
||||
Assert.DoesNotContain("public", response.Headers.CacheControl?.ToString());
|
||||
Assert.Contains("Cookie", response.Headers.Vary);
|
||||
Assert.Single(_apiFactory.StreamingApiClientStub.GetEndpointsCalled);
|
||||
Assert.Equal(expectedEndpoint, _apiFactory.StreamingApiClientStub.GetEndpointsCalled[0]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StreamMusicTrackSegment_WhenDeliveryIdIsInvalid_ShouldReturnNotFoundWithoutCallingTheApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.StreamingApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync(BuildBrowserPath(Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid().ToString("N").ToUpperInvariant(), 0));
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
Assert.Equal(string.Empty, content);
|
||||
Assert.Empty(_apiFactory.StreamingApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(HttpStatusCode.ServiceUnavailable)] // A busy normalization pipeline is a transient condition.
|
||||
[InlineData(HttpStatusCode.TooManyRequests)] // The stream concurrency limit was reached.
|
||||
public async Task StreamMusicTrackSegment_WhenApiReportsATransientCondition_ShouldReturnABareStatus(HttpStatusCode statusCode)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.StreamingApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
string deliveryId = Guid.NewGuid().ToString("N");
|
||||
string expectedEndpoint = BuildExpectedEndpoint(libraryId, artistId, albumId, trackId, deliveryId, 0);
|
||||
_apiFactory.StreamingApiClientStub.RegisterStreamException(expectedEndpoint, new ApiException(
|
||||
new ProblemDetailsDto { Title = "General.Failure", Detail = "InternalServerError", Status = (int)statusCode },
|
||||
statusCode,
|
||||
expectedEndpoint));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync(BuildBrowserPath(libraryId, artistId, albumId, trackId, deliveryId, 0));
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(statusCode, response.StatusCode);
|
||||
Assert.Equal(string.Empty, content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StreamMusicTrackSegment_WhenNotAuthenticated_ShouldRedirectToLoginWithoutCallingTheApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.StreamingApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.GetAsync(BuildBrowserPath(Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid().ToString("N"), 0));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Empty(_apiFactory.StreamingApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the browser facing route of a single segment of the normalized audio of a track.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the track belongs to.</param>
|
||||
/// <param name="artistId">The Id of the artist the album belongs to.</param>
|
||||
/// <param name="albumId">The Id of the album the track belongs to.</param>
|
||||
/// <param name="trackId">The Id of the track.</param>
|
||||
/// <param name="deliveryId">The opaque handle of the normalized delivery.</param>
|
||||
/// <param name="segmentIndex">The zero based index of the segment.</param>
|
||||
/// <returns>The browser facing route of the requested segment.</returns>
|
||||
private static string BuildBrowserPath(Guid libraryId, Guid artistId, Guid albumId, Guid trackId, string deliveryId, int segmentIndex)
|
||||
{
|
||||
return $"/en-us/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-stream-track-segment/{deliveryId}/{segmentIndex}?libraryId={libraryId}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the upstream endpoint the segment request is expected to be sent to.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the track belongs to.</param>
|
||||
/// <param name="artistId">The Id of the artist the album belongs to.</param>
|
||||
/// <param name="albumId">The Id of the album the track belongs to.</param>
|
||||
/// <param name="trackId">The Id of the track.</param>
|
||||
/// <param name="deliveryId">The opaque handle of the normalized delivery.</param>
|
||||
/// <param name="segmentIndex">The zero based index of the segment.</param>
|
||||
/// <returns>The expected upstream endpoint.</returns>
|
||||
private static string BuildExpectedEndpoint(Guid libraryId, Guid artistId, Guid albumId, Guid trackId, string deliveryId, int segmentIndex)
|
||||
{
|
||||
return ApiRoutes.Music.STREAM_TRACK_SEGMENT
|
||||
.Replace("{libraryId}", libraryId.ToString())
|
||||
.Replace("{artistId}", artistId.ToString())
|
||||
.Replace("{albumId}", albumId.ToString())
|
||||
.Replace("{trackId}", trackId.ToString())
|
||||
.Replace("{deliveryId}", deliveryId)
|
||||
.Replace("{segmentIndex}", segmentIndex.ToString(CultureInfo.InvariantCulture));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a streamed API response with a partial content status, a body and the segment headers.
|
||||
/// </summary>
|
||||
/// <param name="contentBytes">The bytes of the content of the response.</param>
|
||||
/// <returns>The created streamed response.</returns>
|
||||
private static async Task<ApiStreamResult> CreateStreamResultAsync(byte[] contentBytes)
|
||||
{
|
||||
HttpResponseMessage response = new(HttpStatusCode.PartialContent)
|
||||
{
|
||||
Content = new ByteArrayContent(contentBytes)
|
||||
};
|
||||
response.Content.Headers.ContentType = new MediaTypeHeaderValue("audio/mp4");
|
||||
response.Headers.CacheControl = new CacheControlHeaderValue { Public = true, MaxAge = TimeSpan.FromSeconds(60) };
|
||||
response.Headers.TryAddWithoutValidation(ApiStreamResult.SEGMENT_COUNT_HEADER_NAME, "9");
|
||||
response.Headers.TryAddWithoutValidation(ApiStreamResult.SEGMENT_START_SECONDS_HEADER_NAME, "6.5");
|
||||
response.Headers.TryAddWithoutValidation(ApiStreamResult.TRACK_DURATION_SECONDS_HEADER_NAME, "300");
|
||||
return await ApiStreamResult.CreateAsync(response, CancellationToken.None);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a deterministic byte array that stands in for the content of a segment.
|
||||
/// </summary>
|
||||
/// <param name="length">The number of bytes to create.</param>
|
||||
/// <returns>The created bytes.</returns>
|
||||
private static byte[] CreateBytes(int length)
|
||||
{
|
||||
return [.. Enumerable.Range(0, length).Select(index => (byte)(index % 256))];
|
||||
}
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.AddLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.AddLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="AddLibraryViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddLibraryViewEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddLibraryViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public AddLibraryViewEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddLibraryView_WhenCalledByAuthenticatedUser_ShouldRenderLibraryAddingView()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/libraries/manage/item");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType);
|
||||
}
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.CancelLibrariesScan;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.CancelLibrariesScan;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="CancelLibrariesScanEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class CancelLibrariesScanEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CancelLibrariesScanEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public CancelLibrariesScanEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CancelLibrariesScan_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldCancelScansAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.RegisterPostSuccess("libraries/scans/cancel");
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage cancelRequest = CreateCancelRequest("/en-us/libraries/manage/api-cancel-libraries-scan");
|
||||
cancelRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(cancelRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "libraries/scans/cancel");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the cancel request that posts an empty JSON body to the given <paramref name="url"/>.
|
||||
/// </summary>
|
||||
/// <param name="url">The URL of the cancel endpoint.</param>
|
||||
/// <returns>The configured cancel request.</returns>
|
||||
private static HttpRequestMessage CreateCancelRequest(string url)
|
||||
{
|
||||
HttpRequestMessage cancelRequest = new(HttpMethod.Post, url)
|
||||
{
|
||||
Content = new StringContent("{}", Encoding.UTF8, "application/json")
|
||||
};
|
||||
// The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted.
|
||||
cancelRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
cancelRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
return cancelRequest;
|
||||
}
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.Management;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.CancelLibraryScan;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.CancelLibraryScan;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="CancelLibraryScanEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class CancelLibraryScanEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CancelLibraryScanEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public CancelLibraryScanEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CancelLibraryScan_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldCancelScanAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid scanId = Guid.NewGuid();
|
||||
_apiFactory.ApiClientStub.RegisterPostPayload<CancelLibraryScanRequest>($"libraries/{libraryId}/scans/{scanId}/cancel");
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage cancelRequest = CreateCancelRequest($"/en-us/libraries/manage/{libraryId}/api-cancel-library-scan/{scanId}");
|
||||
cancelRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(cancelRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PostRequests, postRequest =>
|
||||
postRequest.Endpoint == $"libraries/{libraryId}/scans/{scanId}/cancel" &&
|
||||
postRequest.Data is CancelLibraryScanRequest forwardedRequest &&
|
||||
forwardedRequest.LibraryId == libraryId &&
|
||||
forwardedRequest.ScanId == scanId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the cancel request that posts an empty JSON body to the given <paramref name="url"/>.
|
||||
/// </summary>
|
||||
/// <param name="url">The URL of the cancel endpoint.</param>
|
||||
/// <returns>The configured cancel request.</returns>
|
||||
private static HttpRequestMessage CreateCancelRequest(string url)
|
||||
{
|
||||
HttpRequestMessage cancelRequest = new(HttpMethod.Post, url)
|
||||
{
|
||||
Content = new StringContent("{}", Encoding.UTF8, "application/json")
|
||||
};
|
||||
// The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted.
|
||||
cancelRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
cancelRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
return cancelRequest;
|
||||
}
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.DeleteLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.DeleteLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="DeleteLibraryEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteLibraryEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteLibraryEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public DeleteLibraryEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteLibrary_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldDeleteLibraryAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
_apiFactory.ApiClientStub.RegisterDeleteSuccess($"libraries/{libraryId}");
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(libraryId);
|
||||
deleteRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Contains(_apiFactory.ApiClientStub.DeleteEndpointsCalled, endpoint => endpoint == $"libraries/{libraryId}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the delete request for the library identified by <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library to delete.</param>
|
||||
/// <returns>The configured delete request.</returns>
|
||||
private static HttpRequestMessage CreateDeleteRequest(Guid libraryId)
|
||||
{
|
||||
HttpRequestMessage deleteRequest = new(HttpMethod.Delete, $"/en-us/libraries/manage/api-item/{libraryId}")
|
||||
{
|
||||
// The front-end sends the JSON content type even for DELETE requests, which triggers the antiforgery validation.
|
||||
Content = new StringContent("{}", Encoding.UTF8, "application/json")
|
||||
};
|
||||
// The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted.
|
||||
deleteRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
deleteRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
return deleteRequest;
|
||||
}
|
||||
}
|
||||
+163
@@ -0,0 +1,163 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Common.DTO.Themes;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.EditLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.EditLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="EditLibraryViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class EditLibraryViewEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly LibraryDtoFixture _libraryDtoFixture = new();
|
||||
private readonly ThemeResponseDtoFixture _themeResponseDtoFixture = new();
|
||||
private readonly ThemeTemplateResponseDtoFixture _themeTemplateResponseDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="EditLibraryViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public EditLibraryViewEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EditLibraryView_WhenCalledByAuthenticatedUser_ShouldRenderLibraryEditingView()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
LibraryDto expectedLibrary = _libraryDtoFixture.Create(id: libraryId, title: "Books", libraryType: "Book");
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}", expectedLibrary);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/libraries/manage/item/{libraryId}");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType);
|
||||
Assert.Contains($"libraries/{libraryId}", _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(true)]
|
||||
[InlineData(false)]
|
||||
public async Task EditLibraryView_WhenLibraryHasHiddenFilesSetting_ShouldRenderTheCheckboxWithItsStoredState(bool shouldSkipHiddenFilesAndDirectoriesDuringScan)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
LibraryDto expectedLibrary = _libraryDtoFixture.Create(
|
||||
id: libraryId,
|
||||
title: "Books",
|
||||
libraryType: "Book",
|
||||
shouldSkipHiddenFilesAndDirectoriesDuringScan: shouldSkipHiddenFilesAndDirectoriesDuringScan);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}", expectedLibrary);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/libraries/manage/item/{libraryId}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
string? checkboxTag = GetCheckboxTag(content, "ShouldSkipHiddenFilesAndDirectoriesDuringScan");
|
||||
Assert.NotNull(checkboxTag);
|
||||
if (shouldSkipHiddenFilesAndDirectoriesDuringScan)
|
||||
Assert.Contains("checked", checkboxTag, StringComparison.OrdinalIgnoreCase);
|
||||
else
|
||||
Assert.DoesNotContain("checked", checkboxTag, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EditLibraryView_WhenThemeProvidesFileSystemBrowserTemplates_ShouldRenderThemedComponent()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
LibraryDto expectedLibrary = _libraryDtoFixture.Create(id: libraryId, title: "Books", libraryType: "Book");
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}", expectedLibrary);
|
||||
ThemeResponseDto theme = _themeResponseDtoFixture.Create(themeId: "lumina-default");
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(ApiRoutes.Themes.GET_CURRENT_THEME, theme);
|
||||
RegisterThemeTemplate(theme, "shared/file-system-browser", "<script type=\"text/plain\" id=\"fsb-template-tree-node\">{{{treeNodeTemplate}}}</script><div id=\"file-system-browser-dialog\">themed</div>");
|
||||
RegisterThemeTemplate(theme, "shared/file-system-browser/tree-node", "<div class=\"tree-node\">{{name}}</div>");
|
||||
RegisterThemeTemplate(theme, "shared/file-system-browser/explorer-item", "<div class=\"e\">{{name}}</div>");
|
||||
RegisterThemeTemplate(theme, "shared/file-system-browser/path-segment", "<li>{{path}}</li>");
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/libraries/manage/item/{libraryId}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Contains("id=\"fsb-template-tree-node\"", content);
|
||||
Assert.Contains("initFileSystemBrowser(", content);
|
||||
Assert.Contains("themed", content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EditLibraryView_WhenThemeDoesNotProvideFileSystemBrowserTemplate_ShouldRenderApplicationFallbackComponent()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
LibraryDto expectedLibrary = _libraryDtoFixture.Create(id: libraryId, title: "Books", libraryType: "Book");
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}", expectedLibrary);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/libraries/manage/item/{libraryId}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Contains("id=\"file-system-browser-dialog\"", content);
|
||||
Assert.DoesNotContain("fsb-template-tree-node", content);
|
||||
Assert.Contains("initFileSystemBrowser(", content);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the rendered checkbox input tag with the provided name, or <see langword="null"/> when it is not present.
|
||||
/// </summary>
|
||||
/// <param name="content">The rendered HTML content.</param>
|
||||
/// <param name="name">The name of the checkbox input.</param>
|
||||
/// <returns>The rendered checkbox input tag, or <see langword="null"/>.</returns>
|
||||
private static string? GetCheckboxTag(string content, string name)
|
||||
{
|
||||
Match match = Regex.Match(content, $@"<input[^>]*name=""{Regex.Escape(name)}""[^>]*>");
|
||||
return match.Success ? match.Value : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers the theme template response returned for the specified page key of the given theme.
|
||||
/// </summary>
|
||||
/// <param name="theme">The theme the template belongs to.</param>
|
||||
/// <param name="pageKey">The page key of the template.</param>
|
||||
/// <param name="template">The template source returned for the document.</param>
|
||||
private void RegisterThemeTemplate(ThemeResponseDto theme, string pageKey, string template)
|
||||
{
|
||||
string endpoint = ApiRoutes.Themes.GET_THEME_TEMPLATE
|
||||
.Replace("{themeId}", theme.ThemeId)
|
||||
.Replace("{*pageKey}", pageKey);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(endpoint, _themeTemplateResponseDtoFixture.Create(theme: theme, template: template));
|
||||
}
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Plugins;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetArtworkProviders;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.GetArtworkProviders;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetArtworkProvidersEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetArtworkProvidersEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly LibraryArtworkProviderDtoFixture _libraryArtworkProviderDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetArtworkProvidersEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetArtworkProvidersEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetArtworkProviders_WhenCalledByAuthenticatedUser_ShouldReturnArtworkProvidersJson()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
LibraryArtworkProviderDto[] expectedProviders =
|
||||
[
|
||||
_libraryArtworkProviderDtoFixture.Create(name: "Artwork Provider One", isEnabled: true, rank: 1),
|
||||
_libraryArtworkProviderDtoFixture.Create(name: "Artwork Provider Two", isEnabled: false, rank: 2)
|
||||
];
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/artwork-providers", expectedProviders);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/libraries/manage/api-get-artwork-providers/{libraryId}");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
JsonElement data = json.RootElement.GetProperty("data");
|
||||
Assert.Equal(2, data.GetArrayLength());
|
||||
Assert.Equal("Artwork Provider One", data[0].GetProperty("name").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetArtworkProviders_WhenCalled_ShouldRequestArtworkProvidersFromApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/artwork-providers", Array.Empty<LibraryArtworkProviderDto>());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/libraries/manage/api-get-artwork-providers/{libraryId}");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Contains($"libraries/{libraryId}/artwork-providers", _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
}
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Plugins;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetBookReaders;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.GetBookReaders;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetBookReadersEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetBookReadersEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly LibraryBookReaderDtoFixture _libraryBookReaderDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetBookReadersEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetBookReadersEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetBookReaders_WhenCalledByAuthenticatedUser_ShouldReturnBookReadersJson()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
LibraryBookReaderDto[] expectedReaders =
|
||||
[
|
||||
_libraryBookReaderDtoFixture.Create(name: "EPUB Reader", isEnabled: true)
|
||||
];
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/book-readers", expectedReaders);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/libraries/manage/api-get-book-readers/{libraryId}");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
JsonElement data = json.RootElement.GetProperty("data");
|
||||
Assert.Equal(1, data.GetArrayLength());
|
||||
Assert.Equal("EPUB Reader", data[0].GetProperty("name").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetBookReaders_WhenCalled_ShouldRequestBookReadersFromApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/book-readers", Array.Empty<LibraryBookReaderDto>());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/libraries/manage/api-get-book-readers/{libraryId}");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Contains($"libraries/{libraryId}/book-readers", _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetBookReaders_WhenNotAuthenticated_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.GetAsync($"/en-us/libraries/manage/api-get-book-readers/{Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
}
|
||||
}
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetEnabledLibraries;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.GetEnabledLibraries;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetEnabledLibrariesEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetEnabledLibrariesEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly LibraryDtoFixture _libraryDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetEnabledLibrariesEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetEnabledLibrariesEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetEnabledLibraries_WhenCalledByAuthenticatedUser_ShouldReturnEnabledLibrariesJson()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
LibraryDto[] expectedLibraries =
|
||||
[
|
||||
_libraryDtoFixture.Create(id: Guid.NewGuid(), title: "Books", libraryType: "Book"),
|
||||
_libraryDtoFixture.Create(id: Guid.NewGuid(), title: "Movies", libraryType: "Video")
|
||||
];
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse("libraries/enabled", expectedLibraries);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/libraries/manage/api-get-enabled-libraries");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
JsonElement data = json.RootElement.GetProperty("data");
|
||||
Assert.Equal(2, data.GetArrayLength());
|
||||
Assert.Equal("Books", data[0].GetProperty("title").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetEnabledLibraries_WhenCalled_ShouldRequestEnabledLibrariesFromApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse("libraries/enabled", Array.Empty<LibraryDto>());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/libraries/manage/api-get-enabled-libraries");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Contains("libraries/enabled", _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
}
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Libraries;
|
||||
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 Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.GetLibraries;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetLibrariesEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetLibrariesEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly LibraryDtoFixture _libraryDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetLibrariesEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetLibrariesEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetLibraries_WhenCalledByAuthenticatedUser_ShouldReturnLibrariesJson()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
LibraryDto[] expectedLibraries =
|
||||
[
|
||||
_libraryDtoFixture.Create(id: Guid.NewGuid(), title: "Books", libraryType: "Book"),
|
||||
_libraryDtoFixture.Create(id: Guid.NewGuid(), title: "Movies", libraryType: "Video")
|
||||
];
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse("libraries", expectedLibraries);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/libraries/manage/api-get-libraries");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
JsonElement data = json.RootElement.GetProperty("data");
|
||||
Assert.Equal(2, data.GetArrayLength());
|
||||
Assert.Equal("Books", data[0].GetProperty("title").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetLibraries_WhenCalledWithoutAuthentication_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.GetAsync("/en-us/libraries/manage/api-get-libraries");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetLibraries_WhenCalled_ShouldRequestLibrariesFromApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse("libraries", Array.Empty<LibraryDto>());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/libraries/manage/api-get-libraries");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Contains("libraries", _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
}
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Plugins;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryTypeArtworkProviders;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.GetLibraryTypeArtworkProviders;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetLibraryTypeArtworkProvidersEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetLibraryTypeArtworkProvidersEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly LibraryArtworkProviderDtoFixture _libraryArtworkProviderDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetLibraryTypeArtworkProvidersEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetLibraryTypeArtworkProvidersEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetLibraryTypeArtworkProviders_WhenCalledByAuthenticatedUser_ShouldReturnProvidersJson()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
string libraryType = "Book";
|
||||
LibraryArtworkProviderDto[] expectedProviders =
|
||||
[
|
||||
_libraryArtworkProviderDtoFixture.Create(name: "EPUB Reader", isEnabled: false)
|
||||
];
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/artwork-providers/{libraryType}", expectedProviders);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/libraries/manage/api-get-library-type-artwork-providers/{libraryType}");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
JsonElement data = json.RootElement.GetProperty("data");
|
||||
Assert.Equal(1, data.GetArrayLength());
|
||||
Assert.Equal("EPUB Reader", data[0].GetProperty("name").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetLibraryTypeArtworkProviders_WhenCalled_ShouldRequestProvidersFromApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
string libraryType = "Book";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/artwork-providers/{libraryType}", Array.Empty<LibraryArtworkProviderDto>());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/libraries/manage/api-get-library-type-artwork-providers/{libraryType}");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Contains($"libraries/artwork-providers/{libraryType}", _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetLibraryTypeArtworkProviders_WhenNotAuthenticated_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.GetAsync("/en-us/libraries/manage/api-get-library-type-artwork-providers/Book");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
}
|
||||
}
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Plugins;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryTypeBookReaders;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.GetLibraryTypeBookReaders;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetLibraryTypeBookReadersEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetLibraryTypeBookReadersEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly LibraryBookReaderDtoFixture _libraryBookReaderDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetLibraryTypeBookReadersEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetLibraryTypeBookReadersEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetLibraryTypeBookReaders_WhenCalledByAuthenticatedUser_ShouldReturnBookReadersJson()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
string libraryType = "Book";
|
||||
LibraryBookReaderDto[] expectedReaders =
|
||||
[
|
||||
_libraryBookReaderDtoFixture.Create(name: "EPUB Reader", isEnabled: false)
|
||||
];
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/book-readers/{libraryType}", expectedReaders);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/libraries/manage/api-get-library-type-book-readers/{libraryType}");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
JsonElement data = json.RootElement.GetProperty("data");
|
||||
Assert.Equal(1, data.GetArrayLength());
|
||||
Assert.Equal("EPUB Reader", data[0].GetProperty("name").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetLibraryTypeBookReaders_WhenCalled_ShouldRequestBookReadersFromApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
string libraryType = "Book";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/book-readers/{libraryType}", Array.Empty<LibraryBookReaderDto>());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/libraries/manage/api-get-library-type-book-readers/{libraryType}");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Contains($"libraries/book-readers/{libraryType}", _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetLibraryTypeBookReaders_WhenNotAuthenticated_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.GetAsync("/en-us/libraries/manage/api-get-library-type-book-readers/Book");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
}
|
||||
}
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Plugins;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryTypeMetadataProviders;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.GetLibraryTypeMetadataProviders;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetLibraryTypeMetadataProvidersEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetLibraryTypeMetadataProvidersEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly LibraryMetadataProviderDtoFixture _libraryMetadataProviderDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetLibraryTypeMetadataProvidersEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetLibraryTypeMetadataProvidersEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetLibraryTypeMetadataProviders_WhenCalledByAuthenticatedUser_ShouldReturnProvidersJson()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
string libraryType = "Book";
|
||||
LibraryMetadataProviderDto[] expectedProviders =
|
||||
[
|
||||
_libraryMetadataProviderDtoFixture.Create(name: "EPUB Reader", isEnabled: false)
|
||||
];
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/metadata-providers/{libraryType}", expectedProviders);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/libraries/manage/api-get-library-type-metadata-providers/{libraryType}");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
JsonElement data = json.RootElement.GetProperty("data");
|
||||
Assert.Equal(1, data.GetArrayLength());
|
||||
Assert.Equal("EPUB Reader", data[0].GetProperty("name").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetLibraryTypeMetadataProviders_WhenCalled_ShouldRequestProvidersFromApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
string libraryType = "Book";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/metadata-providers/{libraryType}", Array.Empty<LibraryMetadataProviderDto>());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/libraries/manage/api-get-library-type-metadata-providers/{libraryType}");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Contains($"libraries/metadata-providers/{libraryType}", _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetLibraryTypeMetadataProviders_WhenNotAuthenticated_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.GetAsync("/en-us/libraries/manage/api-get-library-type-metadata-providers/Book");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
}
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Plugins;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetMetadataProviders;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.GetMetadataProviders;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetMetadataProvidersEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetMetadataProvidersEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly LibraryMetadataProviderDtoFixture _libraryMetadataProviderDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetMetadataProvidersEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetMetadataProvidersEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataProviders_WhenCalledByAuthenticatedUser_ShouldReturnMetadataProvidersJson()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
LibraryMetadataProviderDto[] expectedProviders =
|
||||
[
|
||||
_libraryMetadataProviderDtoFixture.Create(name: "Metadata Provider One", isEnabled: true, rank: 1),
|
||||
_libraryMetadataProviderDtoFixture.Create(name: "Metadata Provider Two", isEnabled: false, rank: 2)
|
||||
];
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/metadata-providers", expectedProviders);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/libraries/manage/api-get-metadata-providers/{libraryId}");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
JsonElement data = json.RootElement.GetProperty("data");
|
||||
Assert.Equal(2, data.GetArrayLength());
|
||||
Assert.Equal("Metadata Provider One", data[0].GetProperty("name").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataProviders_WhenCalled_ShouldRequestMetadataProvidersFromApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/metadata-providers", Array.Empty<LibraryMetadataProviderDto>());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/libraries/manage/api-get-metadata-providers/{libraryId}");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Contains($"libraries/{libraryId}/metadata-providers", _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
}
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetRunningLibraryScans;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.GetRunningLibraryScans;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetRunningLibraryScansEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetRunningLibraryScansEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly LibraryScanProgressDtoFixture _libraryScanProgressDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetRunningLibraryScansEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetRunningLibraryScansEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRunningLibraryScans_WhenCalledByAuthenticatedUser_ShouldReturnRunningLibraryScansJson()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
LibraryScanProgressDto[] expectedScans =
|
||||
[
|
||||
_libraryScanProgressDtoFixture.Create(includeCurrentJobProgress: true),
|
||||
_libraryScanProgressDtoFixture.Create()
|
||||
];
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse("libraries/scans/running", expectedScans);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/libraries/manage/api-get-running-library-scans");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
JsonElement data = json.RootElement.GetProperty("data");
|
||||
Assert.Equal(2, data.GetArrayLength());
|
||||
Assert.Equal(JsonValueKind.Object, data[0].GetProperty("currentJobProgress").ValueKind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRunningLibraryScans_WhenCalled_ShouldRequestRunningLibraryScansFromApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse("libraries/scans/running", Array.Empty<LibraryScanProgressDto>());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/libraries/manage/api-get-running-library-scans");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Contains("libraries/scans/running", _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
}
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Enums.Authorization;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.Index;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.Index;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="LibrariesIndexViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LibrariesIndexViewEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LibrariesIndexViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public LibrariesIndexViewEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task LibrariesIndexView_WhenCalledByAuthenticatedUser_ShouldRenderLibrariesManagementView()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/libraries/manage");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("/en-us/libraries/manage", "%2Fen-us%2Flibraries%2Fmanage")] // Plain page.
|
||||
[InlineData("/en-us/libraries/manage?tab=scans", "%2Fen-us%2Flibraries%2Fmanage%3Ftab%3Dscans")] // Query string is kept.
|
||||
public async Task LibrariesIndexView_WhenNavigatedToWithoutAuthentication_ShouldRedirectToLoginWithRequestedPageAsReturnUrl(string requestedUrl, string expectedEncodedReturnUrl)
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
HttpRequestMessage request = new(HttpMethod.Get, requestedUrl);
|
||||
request.Headers.Accept.ParseAdd("text/html");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.SendAsync(request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Equal($"http://localhost/en-us/auth/login?returnUrl={expectedEncodedReturnUrl}", response.Headers.Location!.ToString());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("User", true, "true")] // The permission lets a user manage the libraries they own.
|
||||
[InlineData("User", false, "false")] // Without the permission, a user cannot change even the libraries they own.
|
||||
[InlineData("Admin", false, "true")] // An administrator can manage every library, with or without the permission.
|
||||
public async Task LibrariesIndexView_WhenRendered_ShouldOfferTheEditAndDeleteActionsOnlyToUsersAllowedToManageLibraries(string role, bool hasManagePermission, string expectedCanManageLibraries)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(
|
||||
userId: Guid.NewGuid(),
|
||||
role: role,
|
||||
permissions: hasManagePermission ? [AuthorizationPermission.CanCreateLibraries] : []);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/libraries/manage");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.Contains($"const canManageLibraries = {expectedCanManageLibraries};", content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task LibrariesIndexView_WhenRenderedInACultureWithNonAsciiLabels_ShouldInjectTheScriptLabelsAsJson()
|
||||
{
|
||||
// Arrange
|
||||
// Razor would encode the non-ASCII letters of a raw label as HTML entities, which the browser shows literally inside a script, while JSON escapes them.
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync("/ro-ro/libraries/manage");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.Contains("\"LibraryDeleted\":\"Biblioteca a fost \\u0219tears\\u0103!\"", content);
|
||||
Assert.DoesNotContain("ștears", content);
|
||||
}
|
||||
}
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Libraries;
|
||||
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 Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.SaveLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="SaveLibraryEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SaveLibraryEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly LibraryDtoFixture _libraryDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SaveLibraryEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public SaveLibraryEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveLibrary_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldSaveLibraryAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
LibraryDto request = _libraryDtoFixture.Create(title: "New Books Library", libraryType: "Book");
|
||||
request.Id = null;
|
||||
LibraryDto expectedResponse = _libraryDtoFixture.Create(id: Guid.NewGuid(), title: request.Title, libraryType: request.LibraryType);
|
||||
_apiFactory.ApiClientStub.RegisterPostResponse("libraries", expectedResponse);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage saveRequest = new(HttpMethod.Post, "/en-us/libraries/manage/api-item")
|
||||
{
|
||||
Content = JsonContent.Create(request)
|
||||
};
|
||||
saveRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
saveRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "libraries");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveLibrary_WhenAProviderChoiceHasNoEnabledState_ShouldForwardItWithoutAState()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid pluginId = Guid.NewGuid();
|
||||
LibraryDto request = _libraryDtoFixture.Create(title: "New Books Library", libraryType: "Book");
|
||||
request.Id = null;
|
||||
_apiFactory.ApiClientStub.RegisterPostResponse("libraries", _libraryDtoFixture.Create(id: Guid.NewGuid(), title: request.Title, libraryType: request.LibraryType));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
// The choice is sent without its enabled state, the way a caller that only reorders the providers would send it.
|
||||
HttpRequestMessage saveRequest = new(HttpMethod.Post, "/en-us/libraries/manage/api-item")
|
||||
{
|
||||
Content = JsonContent.Create(new
|
||||
{
|
||||
request.Title,
|
||||
request.LibraryType,
|
||||
request.ContentLocations,
|
||||
MetadataProviders = new[] { new { PluginId = pluginId } }
|
||||
})
|
||||
};
|
||||
saveRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
saveRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
(string _, object? data) = Assert.Single(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "libraries");
|
||||
LibraryDto forwardedLibrary = Assert.IsType<LibraryDto>(data);
|
||||
LibraryProviderSelectionDto forwardedChoice = Assert.Single(forwardedLibrary.MetadataProviders!);
|
||||
Assert.Equal(pluginId, forwardedChoice.PluginId);
|
||||
Assert.Null(forwardedChoice.IsEnabled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveLibrary_WhenCalledWithoutAntiforgeryToken_ShouldReturnBadRequest()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage saveRequest = new(HttpMethod.Post, "/en-us/libraries/manage/api-item")
|
||||
{
|
||||
Content = JsonContent.Create(_libraryDtoFixture.Create(title: "New Books Library", libraryType: "Book"))
|
||||
};
|
||||
saveRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
saveRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "libraries");
|
||||
}
|
||||
}
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.ScanLibraries;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.ScanLibraries;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="ScanLibrariesEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ScanLibrariesEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly ScanLibraryDtoFixture _scanLibraryDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ScanLibrariesEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public ScanLibrariesEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ScanLibraries_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldInitiateScanAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ScanLibraryDto[] expectedScans =
|
||||
[
|
||||
_scanLibraryDtoFixture.Create(libraryId: libraryId)
|
||||
];
|
||||
_apiFactory.ApiClientStub.RegisterPostResponse("libraries/scans", expectedScans);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage scanRequest = CreateScanRequest("/en-us/libraries/manage/api-scan-libraries");
|
||||
scanRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(scanRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(1, json.RootElement.GetProperty("data").GetArrayLength());
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "libraries/scans");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the scan request that posts an empty JSON body to the given <paramref name="url"/>.
|
||||
/// </summary>
|
||||
/// <param name="url">The URL of the scan endpoint.</param>
|
||||
/// <returns>The configured scan request.</returns>
|
||||
private static HttpRequestMessage CreateScanRequest(string url)
|
||||
{
|
||||
HttpRequestMessage scanRequest = new(HttpMethod.Post, url)
|
||||
{
|
||||
Content = new StringContent("{}", Encoding.UTF8, "application/json")
|
||||
};
|
||||
// The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted.
|
||||
scanRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
scanRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
return scanRequest;
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.ScanLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.ScanLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="ScanLibraryEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ScanLibraryEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly ScanLibraryDtoFixture _scanLibraryDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ScanLibraryEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public ScanLibraryEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ScanLibrary_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldInitiateScanAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ScanLibraryDto expectedScan = _scanLibraryDtoFixture.Create(libraryId: libraryId);
|
||||
_apiFactory.ApiClientStub.RegisterPostResponse($"libraries/{libraryId}/scans", expectedScan);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage scanRequest = CreateScanRequest($"/en-us/libraries/manage/api-scan-library/{libraryId}");
|
||||
scanRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(scanRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(libraryId, json.RootElement.GetProperty("data").GetProperty("libraryId").GetGuid());
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == $"libraries/{libraryId}/scans");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the scan request that posts an empty JSON body to the given <paramref name="url"/>.
|
||||
/// </summary>
|
||||
/// <param name="url">The URL of the scan endpoint.</param>
|
||||
/// <returns>The configured scan request.</returns>
|
||||
private static HttpRequestMessage CreateScanRequest(string url)
|
||||
{
|
||||
HttpRequestMessage scanRequest = new(HttpMethod.Post, url)
|
||||
{
|
||||
Content = new StringContent("{}", Encoding.UTF8, "application/json")
|
||||
};
|
||||
// The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted.
|
||||
scanRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
scanRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
return scanRequest;
|
||||
}
|
||||
}
|
||||
+154
@@ -0,0 +1,154 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.Statistics;
|
||||
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 Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Statistics.ClearConsumptionHistory;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="ClearConsumptionHistoryEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ClearConsumptionHistoryEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private static readonly string s_userId = Guid.NewGuid().ToString();
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly ClearConsumptionHistoryRequestFixture _clearConsumptionHistoryRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ClearConsumptionHistoryEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public ClearConsumptionHistoryEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearConsumptionHistory_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldDeleteCurrentUserHistoryAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
ClearConsumptionHistoryRequest request = _clearConsumptionHistoryRequestFixture.Create(includeUserId: false);
|
||||
string expectedUpstreamPath = BuildExpectedUpstreamPath(request);
|
||||
_apiFactory.ApiClientStub.RegisterDeleteSuccess(expectedUpstreamPath);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(BuildRequestPath(request));
|
||||
deleteRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.False(json.RootElement.TryGetProperty("data", out _));
|
||||
Assert.Equal([expectedUpstreamPath], _apiFactory.ApiClientStub.DeleteEndpointsCalled);
|
||||
Assert.True(response.Headers.CacheControl?.NoStore);
|
||||
Assert.True(response.Headers.CacheControl?.Private);
|
||||
Assert.Contains("Cookie", response.Headers.Vary);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearConsumptionHistory_WhenUserIdIsProvided_ShouldDeleteSelectedUserHistory()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
ClearConsumptionHistoryRequest request = _clearConsumptionHistoryRequestFixture.Create(userId: s_userId);
|
||||
string expectedUpstreamPath = BuildExpectedUpstreamPath(request);
|
||||
_apiFactory.ApiClientStub.RegisterDeleteSuccess(expectedUpstreamPath);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(BuildRequestPath(request));
|
||||
deleteRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal([$"users/{s_userId}/consumption-history"], _apiFactory.ApiClientStub.DeleteEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearConsumptionHistory_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
ClearConsumptionHistoryRequest request = _clearConsumptionHistoryRequestFixture.Create(userId: s_userId);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(BuildRequestPath(request));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Empty(_apiFactory.ApiClientStub.DeleteEndpointsCalled);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the path of the Web route that clears the consumption history described by <paramref name="request"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request describing the history to clear.</param>
|
||||
/// <returns>The path of the Web route, including the optional query string.</returns>
|
||||
private static string BuildRequestPath(ClearConsumptionHistoryRequest request)
|
||||
{
|
||||
return string.IsNullOrWhiteSpace(request.UserId)
|
||||
? "/en-us/library/statistics/api-clear-consumption-history"
|
||||
: $"/en-us/library/statistics/api-clear-consumption-history?userId={Uri.EscapeDataString(request.UserId)}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the upstream API path that is expected for <paramref name="request"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request describing the history to clear.</param>
|
||||
/// <returns>The upstream API path, including the optional escaped user identifier.</returns>
|
||||
private static string BuildExpectedUpstreamPath(ClearConsumptionHistoryRequest request)
|
||||
{
|
||||
return string.IsNullOrWhiteSpace(request.UserId)
|
||||
? "users/me/consumption-history"
|
||||
: $"users/{Uri.EscapeDataString(request.UserId)}/consumption-history";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds a DELETE request for <paramref name="path"/> that carries the JSON content type required by the antiforgery middleware.
|
||||
/// </summary>
|
||||
/// <param name="path">The path of the Web route to call.</param>
|
||||
/// <returns>The configured DELETE request.</returns>
|
||||
private static HttpRequestMessage CreateDeleteRequest(string path)
|
||||
{
|
||||
HttpRequestMessage deleteRequest = new(HttpMethod.Delete, path)
|
||||
{
|
||||
Content = new StringContent("{}", Encoding.UTF8, "application/json")
|
||||
};
|
||||
// The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted.
|
||||
deleteRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
deleteRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
return deleteRequest;
|
||||
}
|
||||
}
|
||||
+164
@@ -0,0 +1,164 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.Statistics;
|
||||
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 Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Statistics.ClearResumePoints;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="ClearResumePointsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ClearResumePointsEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private static readonly string s_userId = Guid.NewGuid().ToString();
|
||||
private static readonly string s_libraryId = Guid.NewGuid().ToString();
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly ClearResumePointsRequestFixture _clearResumePointsRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ClearResumePointsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public ClearResumePointsEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearResumePoints_WhenCalledForCurrentUser_ShouldDeleteCurrentUserResumePointsAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
ClearResumePointsRequest request = _clearResumePointsRequestFixture.Create(includeUserId: false, includeLibraryId: false);
|
||||
string expectedUpstreamPath = BuildExpectedUpstreamPath(request);
|
||||
_apiFactory.ApiClientStub.RegisterDeleteSuccess(expectedUpstreamPath);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(BuildRequestPath(request));
|
||||
deleteRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.False(json.RootElement.TryGetProperty("data", out _));
|
||||
Assert.Equal(["users/me/media-resume-points"], _apiFactory.ApiClientStub.DeleteEndpointsCalled);
|
||||
Assert.True(response.Headers.CacheControl?.NoStore);
|
||||
Assert.True(response.Headers.CacheControl?.Private);
|
||||
Assert.Contains("Cookie", response.Headers.Vary);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearResumePoints_WhenUserAndLibraryAreProvided_ShouldDeleteSelectedUserResumePointsWithLibraryFilter()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
ClearResumePointsRequest request = _clearResumePointsRequestFixture.Create(userId: s_userId, libraryId: s_libraryId);
|
||||
string expectedUpstreamPath = BuildExpectedUpstreamPath(request);
|
||||
_apiFactory.ApiClientStub.RegisterDeleteSuccess(expectedUpstreamPath);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(BuildRequestPath(request));
|
||||
deleteRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal([$"users/{s_userId}/media-resume-points?libraryId={s_libraryId}"], _apiFactory.ApiClientStub.DeleteEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearResumePoints_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
ClearResumePointsRequest request = _clearResumePointsRequestFixture.Create(userId: s_userId, libraryId: s_libraryId);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(BuildRequestPath(request));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Empty(_apiFactory.ApiClientStub.DeleteEndpointsCalled);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the path of the Web route that clears the resume points described by <paramref name="request"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request describing the resume points to clear.</param>
|
||||
/// <returns>The path of the Web route, including the optional query string.</returns>
|
||||
private static string BuildRequestPath(ClearResumePointsRequest request)
|
||||
{
|
||||
List<string> parameters = [];
|
||||
if (!string.IsNullOrWhiteSpace(request.UserId))
|
||||
parameters.Add($"userId={Uri.EscapeDataString(request.UserId)}");
|
||||
if (!string.IsNullOrWhiteSpace(request.LibraryId))
|
||||
parameters.Add($"libraryId={Uri.EscapeDataString(request.LibraryId)}");
|
||||
return parameters.Count == 0
|
||||
? "/en-us/library/statistics/api-clear-resume-points"
|
||||
: $"/en-us/library/statistics/api-clear-resume-points?{string.Join("&", parameters)}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the upstream API path that is expected for <paramref name="request"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request describing the resume points to clear.</param>
|
||||
/// <returns>The upstream API path, including the optional escaped identifiers.</returns>
|
||||
private static string BuildExpectedUpstreamPath(ClearResumePointsRequest request)
|
||||
{
|
||||
string path = string.IsNullOrWhiteSpace(request.UserId)
|
||||
? "users/me/media-resume-points"
|
||||
: $"users/{Uri.EscapeDataString(request.UserId)}/media-resume-points";
|
||||
if (!string.IsNullOrWhiteSpace(request.LibraryId))
|
||||
path += $"?libraryId={Uri.EscapeDataString(request.LibraryId)}";
|
||||
return path;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds a DELETE request for <paramref name="path"/> that carries the JSON content type required by the antiforgery middleware.
|
||||
/// </summary>
|
||||
/// <param name="path">The path of the Web route to call.</param>
|
||||
/// <returns>The configured DELETE request.</returns>
|
||||
private static HttpRequestMessage CreateDeleteRequest(string path)
|
||||
{
|
||||
HttpRequestMessage deleteRequest = new(HttpMethod.Delete, path)
|
||||
{
|
||||
Content = new StringContent("{}", Encoding.UTF8, "application/json")
|
||||
};
|
||||
// The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted.
|
||||
deleteRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
deleteRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
return deleteRequest;
|
||||
}
|
||||
}
|
||||
+162
@@ -0,0 +1,162 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Enums.MediaConsumption;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.Statistics;
|
||||
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 Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Statistics.DeleteConsumptionItemHistory;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="DeleteConsumptionItemHistoryEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteConsumptionItemHistoryEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private static readonly string s_userId = Guid.NewGuid().ToString();
|
||||
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 LuminaWebFactory _apiFactory;
|
||||
private readonly DeleteConsumptionItemHistoryRequestFixture _deleteConsumptionItemHistoryRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteConsumptionItemHistoryEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public DeleteConsumptionItemHistoryEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteConsumptionItemHistory_WhenCalledForCurrentUser_ShouldDeleteCurrentUserItemHistoryAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
DeleteConsumptionItemHistoryRequest request = _deleteConsumptionItemHistoryRequestFixture.Create(
|
||||
includeUserId: false,
|
||||
mediaKind: MediaKind.Movie,
|
||||
mediaItemId: s_mediaItemId,
|
||||
libraryId: s_libraryId);
|
||||
string expectedUpstreamPath = $"users/me/consumption-history/media-items/Movie/{s_mediaItemId}/{s_libraryId}";
|
||||
_apiFactory.ApiClientStub.RegisterDeleteSuccess(expectedUpstreamPath);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(BuildRequestPath(request));
|
||||
deleteRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.False(json.RootElement.TryGetProperty("data", out _));
|
||||
Assert.Equal([expectedUpstreamPath], _apiFactory.ApiClientStub.DeleteEndpointsCalled);
|
||||
Assert.True(response.Headers.CacheControl?.NoStore);
|
||||
Assert.True(response.Headers.CacheControl?.Private);
|
||||
Assert.Contains("Cookie", response.Headers.Vary);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteConsumptionItemHistory_WhenUserIsProvided_ShouldDeleteSelectedUserItemHistory()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
DeleteConsumptionItemHistoryRequest request = _deleteConsumptionItemHistoryRequestFixture.Create(
|
||||
userId: s_userId,
|
||||
mediaKind: MediaKind.Book,
|
||||
mediaItemId: s_mediaItemId,
|
||||
libraryId: s_libraryId);
|
||||
string expectedUpstreamPath = $"users/{s_userId}/consumption-history/media-items/Book/{s_mediaItemId}/{s_libraryId}";
|
||||
_apiFactory.ApiClientStub.RegisterDeleteSuccess(expectedUpstreamPath);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(BuildRequestPath(request));
|
||||
deleteRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal([expectedUpstreamPath], _apiFactory.ApiClientStub.DeleteEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteConsumptionItemHistory_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
DeleteConsumptionItemHistoryRequest request = _deleteConsumptionItemHistoryRequestFixture.Create(
|
||||
userId: s_userId,
|
||||
mediaKind: MediaKind.Movie,
|
||||
mediaItemId: s_mediaItemId,
|
||||
libraryId: s_libraryId);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(BuildRequestPath(request));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Empty(_apiFactory.ApiClientStub.DeleteEndpointsCalled);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the path of the Web route that deletes the item history described by <paramref name="request"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request describing the item history to delete.</param>
|
||||
/// <returns>The path of the Web route, including the query string.</returns>
|
||||
private static string BuildRequestPath(DeleteConsumptionItemHistoryRequest request)
|
||||
{
|
||||
List<string> parameters = [];
|
||||
if (!string.IsNullOrWhiteSpace(request.UserId))
|
||||
parameters.Add($"userId={Uri.EscapeDataString(request.UserId)}");
|
||||
parameters.Add($"mediaKind={Uri.EscapeDataString(request.MediaKind.ToString())}");
|
||||
parameters.Add($"mediaItemId={request.MediaItemId}");
|
||||
parameters.Add($"libraryId={request.LibraryId}");
|
||||
return $"/en-us/library/statistics/api-delete-consumption-item-history?{string.Join("&", parameters)}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds a DELETE request for <paramref name="path"/> that carries the JSON content type required by the antiforgery middleware.
|
||||
/// </summary>
|
||||
/// <param name="path">The path of the Web route to call.</param>
|
||||
/// <returns>The configured DELETE request.</returns>
|
||||
private static HttpRequestMessage CreateDeleteRequest(string path)
|
||||
{
|
||||
HttpRequestMessage deleteRequest = new(HttpMethod.Delete, path)
|
||||
{
|
||||
Content = new StringContent("{}", Encoding.UTF8, "application/json")
|
||||
};
|
||||
// The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted.
|
||||
deleteRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
deleteRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
return deleteRequest;
|
||||
}
|
||||
}
|
||||
+163
@@ -0,0 +1,163 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
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.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.Responses.Authorization;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Statistics.GetAllUsersConsumptionStatistics;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetAllUsersConsumptionStatisticsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetAllUsersConsumptionStatisticsEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private static readonly string s_libraryId = "22222222-2222-2222-2222-222222222222";
|
||||
private static readonly DateTime s_fromUtc = new(2024, 3, 4, 5, 6, 7);
|
||||
private static readonly DateTime s_toUtc = new(2025, 6, 7, 8, 9, 10);
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly GetAllUsersConsumptionStatisticsRequestFixture _getAllUsersConsumptionStatisticsRequestFixture = new();
|
||||
private readonly AllUsersConsumptionStatisticsDtoFixture _allUsersConsumptionStatisticsDtoFixture = new();
|
||||
private readonly ConsumptionTotalsDtoFixture _consumptionTotalsDtoFixture = new();
|
||||
private readonly ConsumptionSummaryDtoFixture _consumptionSummaryDtoFixture = new();
|
||||
private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetAllUsersConsumptionStatisticsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetAllUsersConsumptionStatisticsEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllUsersConsumptionStatistics_WhenCalledByAdminWithAllFilters_ShouldReturnStatisticsJson()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []);
|
||||
GetAllUsersConsumptionStatisticsRequest request = _getAllUsersConsumptionStatisticsRequestFixture.Create(
|
||||
libraryId: s_libraryId,
|
||||
mediaKind: MediaKind.Movie,
|
||||
fromUtc: s_fromUtc,
|
||||
toUtc: s_toUtc);
|
||||
const string EXPECTED_UPSTREAM_PATH = "users/consumption-statistics?libraryId=22222222-2222-2222-2222-222222222222&mediaKind=Movie&fromUtc=2024-03-04T05%3A06%3A07.0000000&toUtc=2025-06-07T08%3A09%3A10.0000000";
|
||||
ConsumptionTotalsDto total = _consumptionTotalsDtoFixture.Create(countedSessionCount: 42, includeMediaKindSummaries: false);
|
||||
ConsumptionSummaryDto userSummary = _consumptionSummaryDtoFixture.Create(countedSessionCount: 7, includeMediaKindSummaries: false);
|
||||
AllUsersConsumptionStatisticsDto expectedStatistics = _allUsersConsumptionStatisticsDtoFixture.Create(total: total, users: [userSummary]);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(EXPECTED_UPSTREAM_PATH, expectedStatistics);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync(BuildRequestPath(request));
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
JsonElement data = json.RootElement.GetProperty("data");
|
||||
Assert.Equal(42, data.GetProperty("total").GetProperty("countedSessionCount").GetInt32());
|
||||
Assert.Equal(1, data.GetProperty("users").GetArrayLength());
|
||||
Assert.Equal(7, data.GetProperty("users")[0].GetProperty("countedSessionCount").GetInt32());
|
||||
Assert.Contains(EXPECTED_UPSTREAM_PATH, _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
Assert.True(response.Headers.CacheControl?.NoStore);
|
||||
Assert.True(response.Headers.CacheControl?.Private);
|
||||
Assert.Contains("Cookie", response.Headers.Vary);
|
||||
Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllUsersConsumptionStatistics_WhenCalledByAdminWithoutFilters_ShouldRequestEveryUserAndHandleEmptyUsers()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []);
|
||||
GetAllUsersConsumptionStatisticsRequest request = _getAllUsersConsumptionStatisticsRequestFixture.Create(
|
||||
includeLibraryId: false,
|
||||
includeMediaKind: false,
|
||||
includeFromUtc: false,
|
||||
includeToUtc: false);
|
||||
const string EXPECTED_UPSTREAM_PATH = "users/consumption-statistics";
|
||||
AllUsersConsumptionStatisticsDto expectedStatistics = _allUsersConsumptionStatisticsDtoFixture.Create(includeUsers: false);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(EXPECTED_UPSTREAM_PATH, expectedStatistics);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync(BuildRequestPath(request));
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.Equal(0, json.RootElement.GetProperty("data").GetProperty("users").GetArrayLength());
|
||||
Assert.Contains(EXPECTED_UPSTREAM_PATH, _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllUsersConsumptionStatistics_WhenCalledByNonAdminUser_ShouldRedirectToAccessDeniedAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []);
|
||||
GetAllUsersConsumptionStatisticsRequest request = _getAllUsersConsumptionStatisticsRequestFixture.Create();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync(BuildRequestPath(request));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Contains("access-denied", response.Headers.Location!.ToString());
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("users/", StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the path of the Web route for <paramref name="request"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request whose filters are forwarded.</param>
|
||||
/// <returns>The path of the Web route, including the query string built from the request filters.</returns>
|
||||
private static string BuildRequestPath(GetAllUsersConsumptionStatisticsRequest request)
|
||||
{
|
||||
List<string> parameters = [];
|
||||
if (!string.IsNullOrWhiteSpace(request.LibraryId))
|
||||
parameters.Add($"libraryId={Uri.EscapeDataString(request.LibraryId)}");
|
||||
if (request.MediaKind is not null)
|
||||
parameters.Add($"mediaKind={Uri.EscapeDataString(request.MediaKind.Value.ToString())}");
|
||||
if (request.FromUtc is not null)
|
||||
parameters.Add($"fromUtc={Uri.EscapeDataString(request.FromUtc.Value.ToString("O", CultureInfo.InvariantCulture))}");
|
||||
if (request.ToUtc is not null)
|
||||
parameters.Add($"toUtc={Uri.EscapeDataString(request.ToUtc.Value.ToString("O", CultureInfo.InvariantCulture))}");
|
||||
return parameters.Count == 0
|
||||
? "/en-us/library/statistics/api-get-all-users-statistics"
|
||||
: $"/en-us/library/statistics/api-get-all-users-statistics?{string.Join("&", parameters)}";
|
||||
}
|
||||
}
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
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.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 Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Statistics.GetConsumptionStatistics;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetConsumptionStatisticsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetConsumptionStatisticsEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private static readonly string s_userId = "11111111-1111-1111-1111-111111111111";
|
||||
private static readonly string s_libraryId = "22222222-2222-2222-2222-222222222222";
|
||||
private static readonly DateTime s_fromUtc = new(2024, 3, 4, 5, 6, 7);
|
||||
private static readonly DateTime s_toUtc = new(2025, 6, 7, 8, 9, 10);
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly GetConsumptionStatisticsRequestFixture _getConsumptionStatisticsRequestFixture = new();
|
||||
private readonly ConsumptionSummaryDtoFixture _consumptionSummaryDtoFixture = new();
|
||||
private readonly MediaKindConsumptionSummaryDtoFixture _mediaKindConsumptionSummaryDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetConsumptionStatisticsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetConsumptionStatisticsEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetConsumptionStatistics_WhenCalledWithoutFilters_ShouldRequestCurrentUserStatistics()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
const string EXPECTED_UPSTREAM_PATH = "users/me/consumption-statistics";
|
||||
GetConsumptionStatisticsRequest request = _getConsumptionStatisticsRequestFixture.Create(
|
||||
includeUserId: false,
|
||||
includeLibraryId: false,
|
||||
includeMediaKind: false,
|
||||
includeFromUtc: false,
|
||||
includeToUtc: false);
|
||||
ConsumptionSummaryDto expectedStatistics = _consumptionSummaryDtoFixture.Create(
|
||||
countedSessionCount: 12,
|
||||
mediaKindSummaries: [_mediaKindConsumptionSummaryDtoFixture.Create(mediaKind: MediaKind.Movie)]);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(EXPECTED_UPSTREAM_PATH, expectedStatistics);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync(BuildRequestPath(request));
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
JsonElement data = json.RootElement.GetProperty("data");
|
||||
Assert.Equal(12, data.GetProperty("countedSessionCount").GetInt32());
|
||||
Assert.Equal(1, data.GetProperty("mediaKindSummaries").GetArrayLength());
|
||||
Assert.Contains(EXPECTED_UPSTREAM_PATH, _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
Assert.True(response.Headers.CacheControl?.NoStore);
|
||||
Assert.True(response.Headers.CacheControl?.Private);
|
||||
Assert.Contains("Cookie", response.Headers.Vary);
|
||||
Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetConsumptionStatistics_WhenUserIdAndAllFiltersAreProvided_ShouldRequestUserStatisticsWithEscapedValues()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
const string EXPECTED_UPSTREAM_PATH = "users/11111111-1111-1111-1111-111111111111/consumption-statistics?libraryId=22222222-2222-2222-2222-222222222222&mediaKind=Movie&fromUtc=2024-03-04T05%3A06%3A07.0000000&toUtc=2025-06-07T08%3A09%3A10.0000000";
|
||||
GetConsumptionStatisticsRequest request = _getConsumptionStatisticsRequestFixture.Create(
|
||||
userId: s_userId,
|
||||
libraryId: s_libraryId,
|
||||
mediaKind: MediaKind.Movie,
|
||||
fromUtc: s_fromUtc,
|
||||
toUtc: s_toUtc);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(EXPECTED_UPSTREAM_PATH, _consumptionSummaryDtoFixture.Create(includeMediaKindSummaries: false));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync(BuildRequestPath(request));
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Contains(EXPECTED_UPSTREAM_PATH, _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the path of the Web route for <paramref name="request"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request whose filters are forwarded.</param>
|
||||
/// <returns>The path of the Web route, including the query string built from the request filters.</returns>
|
||||
private static string BuildRequestPath(GetConsumptionStatisticsRequest request)
|
||||
{
|
||||
List<string> parameters = [];
|
||||
if (!string.IsNullOrWhiteSpace(request.UserId))
|
||||
parameters.Add($"userId={Uri.EscapeDataString(request.UserId)}");
|
||||
if (!string.IsNullOrWhiteSpace(request.LibraryId))
|
||||
parameters.Add($"libraryId={Uri.EscapeDataString(request.LibraryId)}");
|
||||
if (request.MediaKind is not null)
|
||||
parameters.Add($"mediaKind={Uri.EscapeDataString(request.MediaKind.Value.ToString())}");
|
||||
if (request.FromUtc is not null)
|
||||
parameters.Add($"fromUtc={Uri.EscapeDataString(request.FromUtc.Value.ToString("O", CultureInfo.InvariantCulture))}");
|
||||
if (request.ToUtc is not null)
|
||||
parameters.Add($"toUtc={Uri.EscapeDataString(request.ToUtc.Value.ToString("O", CultureInfo.InvariantCulture))}");
|
||||
return parameters.Count == 0
|
||||
? "/en-us/library/statistics/api-get-statistics"
|
||||
: $"/en-us/library/statistics/api-get-statistics?{string.Join("&", parameters)}";
|
||||
}
|
||||
}
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
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.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 Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Statistics.GetGenreConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetGenreConsumptionEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetGenreConsumptionEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private static readonly string s_userId = "11111111-1111-1111-1111-111111111111";
|
||||
private static readonly string s_libraryId = "22222222-2222-2222-2222-222222222222";
|
||||
private static readonly DateTime s_fromUtc = new(2024, 3, 4, 5, 6, 7);
|
||||
private static readonly DateTime s_toUtc = new(2025, 6, 7, 8, 9, 10);
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly GetGenreConsumptionRequestFixture _getGenreConsumptionRequestFixture = new();
|
||||
private readonly GenreConsumptionDtoFixture _genreConsumptionDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetGenreConsumptionEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetGenreConsumptionEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetGenreConsumption_WhenUserIdAndAllFiltersAreProvided_ShouldReturnGenreConsumptionJson()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
const string EXPECTED_UPSTREAM_PATH = "users/11111111-1111-1111-1111-111111111111/consumption-statistics/genres?libraryId=22222222-2222-2222-2222-222222222222&mediaKind=Movie&fromUtc=2024-03-04T05%3A06%3A07.0000000&toUtc=2025-06-07T08%3A09%3A10.0000000";
|
||||
GetGenreConsumptionRequest request = _getGenreConsumptionRequestFixture.Create(
|
||||
userId: s_userId,
|
||||
libraryId: s_libraryId,
|
||||
mediaKind: MediaKind.Movie,
|
||||
fromUtc: s_fromUtc,
|
||||
toUtc: s_toUtc);
|
||||
GenreConsumptionDto[] expectedGenres = [_genreConsumptionDtoFixture.Create(name: "drama", consumedItemCount: 3)];
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(EXPECTED_UPSTREAM_PATH, expectedGenres);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync(BuildRequestPath(request));
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
JsonElement data = json.RootElement.GetProperty("data");
|
||||
Assert.Equal(1, data.GetArrayLength());
|
||||
Assert.Equal("drama", data[0].GetProperty("name").GetString());
|
||||
Assert.Equal(3, data[0].GetProperty("consumedItemCount").GetInt32());
|
||||
Assert.Contains(EXPECTED_UPSTREAM_PATH, _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
Assert.True(response.Headers.CacheControl?.NoStore);
|
||||
Assert.True(response.Headers.CacheControl?.Private);
|
||||
Assert.Contains("Cookie", response.Headers.Vary);
|
||||
Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetGenreConsumption_WhenCalledWithoutFilters_ShouldRequestCurrentUserGenresAndHandleEmptyResult()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
const string EXPECTED_UPSTREAM_PATH = "users/me/consumption-statistics/genres";
|
||||
GetGenreConsumptionRequest request = _getGenreConsumptionRequestFixture.Create(
|
||||
includeUserId: false,
|
||||
includeLibraryId: false,
|
||||
includeMediaKind: false,
|
||||
includeFromUtc: false,
|
||||
includeToUtc: false);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(EXPECTED_UPSTREAM_PATH, Array.Empty<GenreConsumptionDto>());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync(BuildRequestPath(request));
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.Equal(0, json.RootElement.GetProperty("data").GetArrayLength());
|
||||
Assert.Contains(EXPECTED_UPSTREAM_PATH, _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the path of the Web route for <paramref name="request"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request whose filters are forwarded.</param>
|
||||
/// <returns>The path of the Web route, including the query string built from the request filters.</returns>
|
||||
private static string BuildRequestPath(GetGenreConsumptionRequest request)
|
||||
{
|
||||
List<string> parameters = [];
|
||||
if (!string.IsNullOrWhiteSpace(request.UserId))
|
||||
parameters.Add($"userId={Uri.EscapeDataString(request.UserId)}");
|
||||
if (!string.IsNullOrWhiteSpace(request.LibraryId))
|
||||
parameters.Add($"libraryId={Uri.EscapeDataString(request.LibraryId)}");
|
||||
if (request.MediaKind is not null)
|
||||
parameters.Add($"mediaKind={Uri.EscapeDataString(request.MediaKind.Value.ToString())}");
|
||||
if (request.FromUtc is not null)
|
||||
parameters.Add($"fromUtc={Uri.EscapeDataString(request.FromUtc.Value.ToString("O", CultureInfo.InvariantCulture))}");
|
||||
if (request.ToUtc is not null)
|
||||
parameters.Add($"toUtc={Uri.EscapeDataString(request.ToUtc.Value.ToString("O", CultureInfo.InvariantCulture))}");
|
||||
return parameters.Count == 0
|
||||
? "/en-us/library/statistics/api-get-genre-consumption"
|
||||
: $"/en-us/library/statistics/api-get-genre-consumption?{string.Join("&", parameters)}";
|
||||
}
|
||||
}
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Libraries;
|
||||
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 Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Statistics.GetLibraries;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetLibrariesEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetLibrariesEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string WEB_ROUTE = "/en-us/library/statistics/api-get-libraries";
|
||||
private const string EXPECTED_UPSTREAM_PATH = "libraries/enabled";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly LibraryDtoFixture _libraryDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetLibrariesEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetLibrariesEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetLibraries_WhenCalledByAuthenticatedUser_ShouldReturnEnabledLibrariesJson()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
LibraryDto[] expectedLibraries =
|
||||
[
|
||||
_libraryDtoFixture.Create(id: Guid.NewGuid(), title: "Books", libraryType: "Book", isEnabled: true),
|
||||
_libraryDtoFixture.Create(id: Guid.NewGuid(), title: "Movies", libraryType: "Video", isEnabled: true)
|
||||
];
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(EXPECTED_UPSTREAM_PATH, expectedLibraries);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync(WEB_ROUTE);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
JsonElement data = json.RootElement.GetProperty("data");
|
||||
Assert.Equal(2, data.GetArrayLength());
|
||||
Assert.Equal("Books", data[0].GetProperty("title").GetString());
|
||||
Assert.Equal("Movies", data[1].GetProperty("title").GetString());
|
||||
Assert.Contains(EXPECTED_UPSTREAM_PATH, _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
Assert.True(response.Headers.CacheControl?.NoStore);
|
||||
Assert.True(response.Headers.CacheControl?.Private);
|
||||
Assert.Contains("Cookie", response.Headers.Vary);
|
||||
Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetLibraries_WhenNoLibrariesExist_ShouldHandleEmptyResult()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(EXPECTED_UPSTREAM_PATH, Array.Empty<LibraryDto>());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync(WEB_ROUTE);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.Equal(0, json.RootElement.GetProperty("data").GetArrayLength());
|
||||
Assert.Contains(EXPECTED_UPSTREAM_PATH, _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
+165
@@ -0,0 +1,165 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
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.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 Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Statistics.GetMostConsumed;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetMostConsumedEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetMostConsumedEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private static readonly string s_userId = "11111111-1111-1111-1111-111111111111";
|
||||
private static readonly string s_libraryId = "22222222-2222-2222-2222-222222222222";
|
||||
private static readonly DateTime s_fromUtc = new(2024, 3, 4, 5, 6, 7);
|
||||
private static readonly DateTime s_toUtc = new(2025, 6, 7, 8, 9, 10);
|
||||
private static readonly Guid s_mediaItemId = Guid.Parse("33333333-3333-3333-3333-333333333333");
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly GetMostConsumedRequestFixture _getMostConsumedRequestFixture = new();
|
||||
private readonly ConsumedItemDtoFixture _consumedItemDtoFixture = new();
|
||||
private readonly PaginatedDtoFixture<ConsumedItemDto> _paginatedDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetMostConsumedEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetMostConsumedEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMostConsumed_WhenUserIdFiltersAndPagingAreProvided_ShouldReturnPageJson()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
const string EXPECTED_UPSTREAM_PATH = "users/11111111-1111-1111-1111-111111111111/consumption-history/most-consumed?libraryId=22222222-2222-2222-2222-222222222222&mediaKind=Movie&fromUtc=2024-03-04T05%3A06%3A07.0000000&toUtc=2025-06-07T08%3A09%3A10.0000000¤tPage=2&perPage=5";
|
||||
GetMostConsumedRequest request = _getMostConsumedRequestFixture.Create(
|
||||
userId: s_userId,
|
||||
libraryId: s_libraryId,
|
||||
mediaKind: MediaKind.Movie,
|
||||
fromUtc: s_fromUtc,
|
||||
toUtc: s_toUtc,
|
||||
currentPage: 2,
|
||||
perPage: 5);
|
||||
PaginatedDto<ConsumedItemDto> expectedPage = _paginatedDtoFixture.Create(
|
||||
data:
|
||||
[
|
||||
_consumedItemDtoFixture.Create(mediaItemId: s_mediaItemId, mediaKind: MediaKind.Movie),
|
||||
_consumedItemDtoFixture.Create(mediaKind: MediaKind.Movie)
|
||||
],
|
||||
currentPage: 2,
|
||||
perPage: 5,
|
||||
count: 12,
|
||||
numberOfPages: 3);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(EXPECTED_UPSTREAM_PATH, expectedPage);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync(BuildRequestPath(request));
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
JsonElement data = json.RootElement.GetProperty("data");
|
||||
Assert.Equal(2, data.GetProperty("data").GetArrayLength());
|
||||
Assert.Equal(2, data.GetProperty("currentPage").GetInt32());
|
||||
Assert.Equal(5, data.GetProperty("perPage").GetInt32());
|
||||
Assert.Equal(s_mediaItemId, data.GetProperty("data")[0].GetProperty("mediaItemId").GetGuid());
|
||||
Assert.Contains(EXPECTED_UPSTREAM_PATH, _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
Assert.True(response.Headers.CacheControl?.NoStore);
|
||||
Assert.True(response.Headers.CacheControl?.Private);
|
||||
Assert.Contains("Cookie", response.Headers.Vary);
|
||||
Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMostConsumed_WhenNoFiltersOrPagingAreProvided_ShouldRequestCurrentUserWithDefaultPaging()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
const string EXPECTED_UPSTREAM_PATH = "users/me/consumption-history/most-consumed?currentPage=1&perPage=10";
|
||||
GetMostConsumedRequest request = _getMostConsumedRequestFixture.Create(
|
||||
includeUserId: false,
|
||||
includeLibraryId: false,
|
||||
includeMediaKind: false,
|
||||
includeFromUtc: false,
|
||||
includeToUtc: false,
|
||||
includeCurrentPage: false,
|
||||
includePerPage: false);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(EXPECTED_UPSTREAM_PATH, _paginatedDtoFixture.Create(data: [], currentPage: 1, perPage: 10));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync(BuildRequestPath(request));
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
JsonElement data = json.RootElement.GetProperty("data");
|
||||
Assert.Equal(0, data.GetProperty("data").GetArrayLength());
|
||||
Assert.Equal(1, data.GetProperty("currentPage").GetInt32());
|
||||
Assert.Equal(10, data.GetProperty("perPage").GetInt32());
|
||||
Assert.Contains(EXPECTED_UPSTREAM_PATH, _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the path of the Web route for <paramref name="request"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request whose filters and paging are forwarded.</param>
|
||||
/// <returns>The path of the Web route, including the query string built from the request values.</returns>
|
||||
private static string BuildRequestPath(GetMostConsumedRequest request)
|
||||
{
|
||||
List<string> parameters = [];
|
||||
if (!string.IsNullOrWhiteSpace(request.UserId))
|
||||
parameters.Add($"userId={Uri.EscapeDataString(request.UserId)}");
|
||||
if (!string.IsNullOrWhiteSpace(request.LibraryId))
|
||||
parameters.Add($"libraryId={Uri.EscapeDataString(request.LibraryId)}");
|
||||
if (request.MediaKind is not null)
|
||||
parameters.Add($"mediaKind={Uri.EscapeDataString(request.MediaKind.Value.ToString())}");
|
||||
if (request.FromUtc is not null)
|
||||
parameters.Add($"fromUtc={Uri.EscapeDataString(request.FromUtc.Value.ToString("O", CultureInfo.InvariantCulture))}");
|
||||
if (request.ToUtc is not null)
|
||||
parameters.Add($"toUtc={Uri.EscapeDataString(request.ToUtc.Value.ToString("O", CultureInfo.InvariantCulture))}");
|
||||
if (request.CurrentPage is not null)
|
||||
parameters.Add($"currentPage={request.CurrentPage.Value.ToString(CultureInfo.InvariantCulture)}");
|
||||
if (request.PerPage is not null)
|
||||
parameters.Add($"perPage={request.PerPage.Value.ToString(CultureInfo.InvariantCulture)}");
|
||||
return parameters.Count == 0
|
||||
? "/en-us/library/statistics/api-get-most-consumed"
|
||||
: $"/en-us/library/statistics/api-get-most-consumed?{string.Join("&", parameters)}";
|
||||
}
|
||||
}
|
||||
+165
@@ -0,0 +1,165 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
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.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 Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Statistics.GetRecentlyConsumed;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetRecentlyConsumedEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetRecentlyConsumedEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private static readonly string s_userId = "11111111-1111-1111-1111-111111111111";
|
||||
private static readonly string s_libraryId = "22222222-2222-2222-2222-222222222222";
|
||||
private static readonly DateTime s_fromUtc = new(2024, 3, 4, 5, 6, 7);
|
||||
private static readonly DateTime s_toUtc = new(2025, 6, 7, 8, 9, 10);
|
||||
private static readonly Guid s_mediaItemId = Guid.Parse("33333333-3333-3333-3333-333333333333");
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly GetRecentlyConsumedRequestFixture _getRecentlyConsumedRequestFixture = new();
|
||||
private readonly ConsumedItemDtoFixture _consumedItemDtoFixture = new();
|
||||
private readonly PaginatedDtoFixture<ConsumedItemDto> _paginatedDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetRecentlyConsumedEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetRecentlyConsumedEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecentlyConsumed_WhenUserIdFiltersAndPagingAreProvided_ShouldReturnPageJson()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
const string EXPECTED_UPSTREAM_PATH = "users/11111111-1111-1111-1111-111111111111/consumption-history/recently-consumed?libraryId=22222222-2222-2222-2222-222222222222&mediaKind=Movie&fromUtc=2024-03-04T05%3A06%3A07.0000000&toUtc=2025-06-07T08%3A09%3A10.0000000¤tPage=2&perPage=5";
|
||||
GetRecentlyConsumedRequest request = _getRecentlyConsumedRequestFixture.Create(
|
||||
userId: s_userId,
|
||||
libraryId: s_libraryId,
|
||||
mediaKind: MediaKind.Movie,
|
||||
fromUtc: s_fromUtc,
|
||||
toUtc: s_toUtc,
|
||||
currentPage: 2,
|
||||
perPage: 5);
|
||||
PaginatedDto<ConsumedItemDto> expectedPage = _paginatedDtoFixture.Create(
|
||||
data:
|
||||
[
|
||||
_consumedItemDtoFixture.Create(mediaItemId: s_mediaItemId, mediaKind: MediaKind.Movie),
|
||||
_consumedItemDtoFixture.Create(mediaKind: MediaKind.Movie)
|
||||
],
|
||||
currentPage: 2,
|
||||
perPage: 5,
|
||||
count: 12,
|
||||
numberOfPages: 3);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(EXPECTED_UPSTREAM_PATH, expectedPage);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync(BuildRequestPath(request));
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
JsonElement data = json.RootElement.GetProperty("data");
|
||||
Assert.Equal(2, data.GetProperty("data").GetArrayLength());
|
||||
Assert.Equal(2, data.GetProperty("currentPage").GetInt32());
|
||||
Assert.Equal(5, data.GetProperty("perPage").GetInt32());
|
||||
Assert.Equal(s_mediaItemId, data.GetProperty("data")[0].GetProperty("mediaItemId").GetGuid());
|
||||
Assert.Contains(EXPECTED_UPSTREAM_PATH, _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
Assert.True(response.Headers.CacheControl?.NoStore);
|
||||
Assert.True(response.Headers.CacheControl?.Private);
|
||||
Assert.Contains("Cookie", response.Headers.Vary);
|
||||
Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecentlyConsumed_WhenNoFiltersOrPagingAreProvided_ShouldRequestCurrentUserWithDefaultPaging()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
const string EXPECTED_UPSTREAM_PATH = "users/me/consumption-history/recently-consumed?currentPage=1&perPage=10";
|
||||
GetRecentlyConsumedRequest request = _getRecentlyConsumedRequestFixture.Create(
|
||||
includeUserId: false,
|
||||
includeLibraryId: false,
|
||||
includeMediaKind: false,
|
||||
includeFromUtc: false,
|
||||
includeToUtc: false,
|
||||
includeCurrentPage: false,
|
||||
includePerPage: false);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(EXPECTED_UPSTREAM_PATH, _paginatedDtoFixture.Create(data: [], currentPage: 1, perPage: 10));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync(BuildRequestPath(request));
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
JsonElement data = json.RootElement.GetProperty("data");
|
||||
Assert.Equal(0, data.GetProperty("data").GetArrayLength());
|
||||
Assert.Equal(1, data.GetProperty("currentPage").GetInt32());
|
||||
Assert.Equal(10, data.GetProperty("perPage").GetInt32());
|
||||
Assert.Contains(EXPECTED_UPSTREAM_PATH, _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the path of the Web route for <paramref name="request"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request whose filters and paging are forwarded.</param>
|
||||
/// <returns>The path of the Web route, including the query string built from the request values.</returns>
|
||||
private static string BuildRequestPath(GetRecentlyConsumedRequest request)
|
||||
{
|
||||
List<string> parameters = [];
|
||||
if (!string.IsNullOrWhiteSpace(request.UserId))
|
||||
parameters.Add($"userId={Uri.EscapeDataString(request.UserId)}");
|
||||
if (!string.IsNullOrWhiteSpace(request.LibraryId))
|
||||
parameters.Add($"libraryId={Uri.EscapeDataString(request.LibraryId)}");
|
||||
if (request.MediaKind is not null)
|
||||
parameters.Add($"mediaKind={Uri.EscapeDataString(request.MediaKind.Value.ToString())}");
|
||||
if (request.FromUtc is not null)
|
||||
parameters.Add($"fromUtc={Uri.EscapeDataString(request.FromUtc.Value.ToString("O", CultureInfo.InvariantCulture))}");
|
||||
if (request.ToUtc is not null)
|
||||
parameters.Add($"toUtc={Uri.EscapeDataString(request.ToUtc.Value.ToString("O", CultureInfo.InvariantCulture))}");
|
||||
if (request.CurrentPage is not null)
|
||||
parameters.Add($"currentPage={request.CurrentPage.Value.ToString(CultureInfo.InvariantCulture)}");
|
||||
if (request.PerPage is not null)
|
||||
parameters.Add($"perPage={request.PerPage.Value.ToString(CultureInfo.InvariantCulture)}");
|
||||
return parameters.Count == 0
|
||||
? "/en-us/library/statistics/api-get-recently-consumed"
|
||||
: $"/en-us/library/statistics/api-get-recently-consumed?{string.Join("&", parameters)}";
|
||||
}
|
||||
}
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
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.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 Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Statistics.GetTagConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetTagConsumptionEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetTagConsumptionEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private static readonly string s_userId = "11111111-1111-1111-1111-111111111111";
|
||||
private static readonly string s_libraryId = "22222222-2222-2222-2222-222222222222";
|
||||
private static readonly DateTime s_fromUtc = new(2024, 3, 4, 5, 6, 7);
|
||||
private static readonly DateTime s_toUtc = new(2025, 6, 7, 8, 9, 10);
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly GetTagConsumptionRequestFixture _getTagConsumptionRequestFixture = new();
|
||||
private readonly TagConsumptionDtoFixture _tagConsumptionDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetTagConsumptionEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetTagConsumptionEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTagConsumption_WhenUserIdAndAllFiltersAreProvided_ShouldReturnTagConsumptionJson()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
const string EXPECTED_UPSTREAM_PATH = "users/11111111-1111-1111-1111-111111111111/consumption-statistics/tags?libraryId=22222222-2222-2222-2222-222222222222&mediaKind=Movie&fromUtc=2024-03-04T05%3A06%3A07.0000000&toUtc=2025-06-07T08%3A09%3A10.0000000";
|
||||
GetTagConsumptionRequest request = _getTagConsumptionRequestFixture.Create(
|
||||
userId: s_userId,
|
||||
libraryId: s_libraryId,
|
||||
mediaKind: MediaKind.Movie,
|
||||
fromUtc: s_fromUtc,
|
||||
toUtc: s_toUtc);
|
||||
TagConsumptionDto[] expectedTags = [_tagConsumptionDtoFixture.Create(name: "favourite", consumedItemCount: 4)];
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(EXPECTED_UPSTREAM_PATH, expectedTags);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync(BuildRequestPath(request));
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
JsonElement data = json.RootElement.GetProperty("data");
|
||||
Assert.Equal(1, data.GetArrayLength());
|
||||
Assert.Equal("favourite", data[0].GetProperty("name").GetString());
|
||||
Assert.Equal(4, data[0].GetProperty("consumedItemCount").GetInt32());
|
||||
Assert.Contains(EXPECTED_UPSTREAM_PATH, _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
Assert.True(response.Headers.CacheControl?.NoStore);
|
||||
Assert.True(response.Headers.CacheControl?.Private);
|
||||
Assert.Contains("Cookie", response.Headers.Vary);
|
||||
Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTagConsumption_WhenCalledWithoutFilters_ShouldRequestCurrentUserTagsAndHandleEmptyResult()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
const string EXPECTED_UPSTREAM_PATH = "users/me/consumption-statistics/tags";
|
||||
GetTagConsumptionRequest request = _getTagConsumptionRequestFixture.Create(
|
||||
includeUserId: false,
|
||||
includeLibraryId: false,
|
||||
includeMediaKind: false,
|
||||
includeFromUtc: false,
|
||||
includeToUtc: false);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(EXPECTED_UPSTREAM_PATH, Array.Empty<TagConsumptionDto>());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync(BuildRequestPath(request));
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.Equal(0, json.RootElement.GetProperty("data").GetArrayLength());
|
||||
Assert.Contains(EXPECTED_UPSTREAM_PATH, _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the path of the Web route for <paramref name="request"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request whose filters are forwarded.</param>
|
||||
/// <returns>The path of the Web route, including the query string built from the request filters.</returns>
|
||||
private static string BuildRequestPath(GetTagConsumptionRequest request)
|
||||
{
|
||||
List<string> parameters = [];
|
||||
if (!string.IsNullOrWhiteSpace(request.UserId))
|
||||
parameters.Add($"userId={Uri.EscapeDataString(request.UserId)}");
|
||||
if (!string.IsNullOrWhiteSpace(request.LibraryId))
|
||||
parameters.Add($"libraryId={Uri.EscapeDataString(request.LibraryId)}");
|
||||
if (request.MediaKind is not null)
|
||||
parameters.Add($"mediaKind={Uri.EscapeDataString(request.MediaKind.Value.ToString())}");
|
||||
if (request.FromUtc is not null)
|
||||
parameters.Add($"fromUtc={Uri.EscapeDataString(request.FromUtc.Value.ToString("O", CultureInfo.InvariantCulture))}");
|
||||
if (request.ToUtc is not null)
|
||||
parameters.Add($"toUtc={Uri.EscapeDataString(request.ToUtc.Value.ToString("O", CultureInfo.InvariantCulture))}");
|
||||
return parameters.Count == 0
|
||||
? "/en-us/library/statistics/api-get-tag-consumption"
|
||||
: $"/en-us/library/statistics/api-get-tag-consumption?{string.Join("&", parameters)}";
|
||||
}
|
||||
}
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.UsersManagement;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetUsers;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.UsersManagement;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Statistics.GetUsers;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetUsersEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetUsersEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string WEB_ROUTE = "/en-us/library/statistics/api-get-users";
|
||||
private const string EXPECTED_UPSTREAM_PATH = "auth/users";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly UserDtoFixture _userDtoFixture = new();
|
||||
private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetUsersEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetUsersEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUsers_WhenCalledByAdminUser_ShouldReturnUsersJson()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []);
|
||||
UserDto[] expectedUsers =
|
||||
[
|
||||
_userDtoFixture.Create(id: Guid.NewGuid(), username: "alice"),
|
||||
_userDtoFixture.Create(id: Guid.NewGuid(), username: "bob")
|
||||
];
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(EXPECTED_UPSTREAM_PATH, expectedUsers);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync(WEB_ROUTE);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
JsonElement data = json.RootElement.GetProperty("data");
|
||||
Assert.Equal(2, data.GetArrayLength());
|
||||
Assert.Equal("alice", data[0].GetProperty("username").GetString());
|
||||
Assert.Equal("bob", data[1].GetProperty("username").GetString());
|
||||
Assert.Contains(EXPECTED_UPSTREAM_PATH, _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
Assert.True(response.Headers.CacheControl?.NoStore);
|
||||
Assert.True(response.Headers.CacheControl?.Private);
|
||||
Assert.Contains("Cookie", response.Headers.Vary);
|
||||
Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUsers_WhenNoUsersExist_ShouldHandleEmptyResult()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(EXPECTED_UPSTREAM_PATH, Array.Empty<UserDto>());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync(WEB_ROUTE);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.Equal(0, json.RootElement.GetProperty("data").GetArrayLength());
|
||||
Assert.Contains(EXPECTED_UPSTREAM_PATH, _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUsers_WhenCalledByNonAdminUser_ShouldRedirectToAccessDeniedAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync(WEB_ROUTE);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Contains("access-denied", response.Headers.Location!.ToString());
|
||||
Assert.DoesNotContain(EXPECTED_UPSTREAM_PATH, _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.Index;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Statistics.Index;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="StatisticsIndexViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class StatisticsIndexViewEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string WEB_ROUTE = "/en-us/library/statistics";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="StatisticsIndexViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public StatisticsIndexViewEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StatisticsIndexView_WhenCalledByRegularUser_ShouldRenderStatisticsPageWithoutUserSelector()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync(WEB_ROUTE);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType);
|
||||
Assert.Contains("statistics-page", content, StringComparison.Ordinal);
|
||||
Assert.Contains("const isAdmin = false;", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("statistics-user-selector", content, StringComparison.Ordinal);
|
||||
Assert.True(response.Headers.CacheControl?.NoStore);
|
||||
Assert.Contains("Cookie", response.Headers.Vary);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("users/", StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StatisticsIndexView_WhenCalledByAnonymousUser_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.GetAsync(WEB_ROUTE);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
|
||||
Assert.Empty(_apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StatisticsIndexView_WhenCalledByAdminUser_ShouldRenderStatisticsPageWithUserSelector()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync(WEB_ROUTE);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType);
|
||||
Assert.Contains("statistics-user-selector", content, StringComparison.Ordinal);
|
||||
Assert.Contains("const isAdmin = true;", content, StringComparison.Ordinal);
|
||||
Assert.Contains("api-get-users", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("users/", StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeleteBook;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeleteBook;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="DeleteBookEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteBookEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteBookEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public DeleteBookEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteBook_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldForwardDeleteAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
_apiFactory.ApiClientStub.RegisterDeleteSuccess($"libraries/{libraryId}/books/{bookId}");
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(bookId, libraryId);
|
||||
deleteRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Contains($"libraries/{libraryId}/books/{bookId}", _apiFactory.ApiClientStub.DeleteEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteBook_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(bookId, libraryId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.DoesNotContain($"libraries/{libraryId}/books/{bookId}", _apiFactory.ApiClientStub.DeleteEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteBook_WhenNotAuthenticated_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(Guid.NewGuid(), Guid.NewGuid());
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.SendAsync(deleteRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Empty(_apiFactory.ApiClientStub.DeleteEndpointsCalled);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the delete request for the book identified by the route, with the owning library passed through the query string.
|
||||
/// </summary>
|
||||
/// <param name="bookId">The route Id of the book to delete.</param>
|
||||
/// <param name="libraryId">The Id of the media library the book belongs to.</param>
|
||||
/// <returns>The configured delete request.</returns>
|
||||
private static HttpRequestMessage CreateDeleteRequest(Guid bookId, Guid libraryId)
|
||||
{
|
||||
HttpRequestMessage deleteRequest = new(HttpMethod.Delete, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-delete-book?libraryId={libraryId}")
|
||||
{
|
||||
// The front-end sends the JSON content type even for DELETE requests, which triggers the antiforgery validation.
|
||||
Content = new StringContent("{}", Encoding.UTF8, "application/json")
|
||||
};
|
||||
// The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted.
|
||||
deleteRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
deleteRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
return deleteRequest;
|
||||
}
|
||||
}
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeletedBooks;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeletedBooks;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="DeletedBooksViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeletedBooksViewEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly LibraryDtoFixture _libraryDtoFixture = new();
|
||||
private readonly DeletedBookDtoFixture _deletedBookDtoFixture = new();
|
||||
private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeletedBooksViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public DeletedBooksViewEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeletedBooksView_WhenCalledByAuthenticatedUserWithLibraryId_ShouldRenderDeletedBooksPage()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
LibraryDto library = _libraryDtoFixture.Create(id: libraryId, title: "Books");
|
||||
DeletedBookDto deletedBook = _deletedBookDtoFixture.Create(libraryId: libraryId, title: "Deleted Book");
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}", library);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/books/deleted-items", new[] { deletedBook });
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/written-content-library/books-library/books/deleted-items?libraryId={libraryId}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType);
|
||||
Assert.Contains("Deleted Book", content);
|
||||
Assert.Contains("deleted-books-table", content);
|
||||
Assert.Contains($"libraries/{libraryId}/books/deleted-items", _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeletedBooksView_WhenDeletedBookTitleContainsMarkup_ShouldEncodeIt()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
LibraryDto library = _libraryDtoFixture.Create(id: libraryId, title: "Books");
|
||||
DeletedBookDto deletedBook = _deletedBookDtoFixture.Create(libraryId: libraryId, title: "<script>alert('x')</script>");
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}", library);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/books/deleted-items", new[] { deletedBook });
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/written-content-library/books-library/books/deleted-items?libraryId={libraryId}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Contains("<script>alert", content);
|
||||
Assert.DoesNotContain("<script>alert('x')</script>", content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeletedBooksView_WhenTheApiReturnsForbidden_ShouldRedirectWithoutLeakingDetails()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
LibraryDto library = _libraryDtoFixture.Create(id: libraryId, title: "Books");
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}", library);
|
||||
string endpoint = $"libraries/{libraryId}/books/deleted-items";
|
||||
_apiFactory.ApiClientStub.RegisterGetException(endpoint, new ApiException(
|
||||
_problemDetailsDtoFixture.Create(title: "General.Unauthorized", detail: "NotAuthorized"),
|
||||
HttpStatusCode.Forbidden,
|
||||
endpoint));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/written-content-library/books-library/books/deleted-items?libraryId={libraryId}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
// A browser navigation that the API forbids is redirected to the access denied page, without rendering any of the forbidden data.
|
||||
Assert.Equal(HttpStatusCode.Found, response.StatusCode);
|
||||
Assert.NotNull(response.Headers.Location);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeletedBooksView_WhenCalledWithoutLibraryId_ShouldRedirectToHome()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/library/written-content-library/books-library/books/deleted-items");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Contains("/en-us", response.Headers.Location!.ToString());
|
||||
}
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.EditBook;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.EditBook;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="EditBookViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class EditBookViewEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly BookDetailsDtoFixture _bookDetailsDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="EditBookViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public EditBookViewEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EditBook_WhenCalledByAuthenticatedUser_ShouldRenderEditBookPage()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create();
|
||||
expectedBook.Metadata!.Title = "A book";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{expectedBook.LibraryId}/books/{expectedBook.Id}", expectedBook);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/written-content-library/books-library/books/{expectedBook.Id}?libraryId={expectedBook.LibraryId}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType);
|
||||
Assert.Contains("A book", content);
|
||||
Assert.Contains("btn-delete-book", content);
|
||||
}
|
||||
}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary;
|
||||
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.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBookDetails;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetBookDetailsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetBookDetailsEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly BookDetailsDtoFixture _bookDetailsDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetBookDetailsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetBookDetailsEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetBookDetails_WhenCalledByAuthenticatedUser_ShouldReturnBookDetailsFromApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create(id: bookId);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/books/{bookId}", expectedBook);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-get-book?libraryId={libraryId}");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(bookId, json.RootElement.GetProperty("data").GetProperty("id").GetGuid());
|
||||
Assert.Contains($"libraries/{libraryId}/books/{bookId}", _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetBookDetails_WhenNotAuthenticated_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.GetAsync($"/en-us/library/written-content-library/books-library/books/{Guid.NewGuid()}/api-get-book?libraryId={Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("libraries/", StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Common.DTO.Libraries;
|
||||
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.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetLibraryItems;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetLibraryItemsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetLibraryItemsEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly PaginatedDtoFixture<BookLiteDto> _paginatedBookLiteDtoFixture = new();
|
||||
private readonly BookLiteDtoFixture _bookLiteDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetLibraryItemsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetLibraryItemsEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetLibraryItems_WhenCalledByAuthenticatedUser_ShouldReturnBooksFromApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
string searchTerm = "Harry";
|
||||
PaginatedDto<BookLiteDto> expectedResponse = _paginatedBookLiteDtoFixture.Create(data: [_bookLiteDtoFixture.Create(title: "Harry Potter")]);
|
||||
string expectedEndpoint = $"libraries/{libraryId}/books/lite?currentPage=1&perPage=20&searchTerm={searchTerm}&shouldIgnoreThePrefixForAlphaPicker=True";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, expectedResponse);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/written-content-library/books-library/books/api-get-library-items?libraryId={libraryId}¤tPage=1&perPage=20&searchTerm={searchTerm}&shouldIgnoreThePrefixForAlphaPicker=true");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(expectedResponse.Data.Count, json.RootElement.GetProperty("data").GetProperty("data").GetArrayLength());
|
||||
Assert.Contains(expectedEndpoint, _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
}
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Index;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Index;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="BooksIndexViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class BooksIndexViewEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly LibraryDtoFixture _libraryDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="BooksIndexViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public BooksIndexViewEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task BooksIndex_WhenCalledByAuthenticatedUserWithLibraryId_ShouldRenderBooksPage()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
LibraryDto expectedLibrary = _libraryDtoFixture.Create(id: libraryId, title: "Books");
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}", expectedLibrary);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/written-content-library/books-library/books?libraryId={libraryId}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType);
|
||||
Assert.Contains("search-input", content);
|
||||
Assert.Contains("card-action-delete", content);
|
||||
Assert.Contains($"libraries/{libraryId}", _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task BooksIndex_WhenTheCultureUsesApostrophes_ShouldSerializeTheLocalizedStringsAsJson()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
LibraryDto expectedLibrary = _libraryDtoFixture.Create(id: libraryId, title: "Livres");
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}", expectedLibrary);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"/fr-fr/library/written-content-library/books-library/books?libraryId={libraryId}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
// The apostrophes and accents are JSON-escaped, so the translations stay valid JavaScript string literals.
|
||||
Assert.Contains("deleteFailed: \"L", content);
|
||||
Assert.Contains("deleteConfirm: \"", content);
|
||||
Assert.DoesNotContain("deleteFailed: '", content);
|
||||
Assert.DoesNotContain("deleteConfirm: '", content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task BooksIndex_WhenCalledByAuthenticatedUserWithoutLibraryId_ShouldRedirectToHome()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/library/written-content-library/books-library/books");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Contains("/en-us", response.Headers.Location!.ToString());
|
||||
}
|
||||
}
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Reading;
|
||||
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.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingAvailability;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetReadingAvailabilityEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetReadingAvailabilityEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly ReadingAvailabilityDtoFixture _readingAvailabilityDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetReadingAvailabilityEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetReadingAvailabilityEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetReadingAvailability_WhenCalledByAuthenticatedUser_ShouldReturnAvailabilityJson()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
ReadingAvailabilityDto availability = _readingAvailabilityDtoFixture.Create(bookId: bookId, isAvailable: true);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/books/{bookId}/reading/availability", availability);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-get-reading-availability?libraryId={libraryId}");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(availability.LibraryId, json.RootElement.GetProperty("libraryId").GetGuid());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetReadingAvailability_WhenCalled_ShouldRequestAvailabilityFromApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/books/{bookId}/reading/availability", _readingAvailabilityDtoFixture.Create(bookId: bookId));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-get-reading-availability?libraryId={libraryId}");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Contains($"libraries/{libraryId}/books/{bookId}/reading/availability", _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetReadingAvailability_WhenNotAuthenticated_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.GetAsync($"/en-us/library/written-content-library/books-library/books/{Guid.NewGuid()}/api-get-reading-availability");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
}
|
||||
}
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Reading;
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
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.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingManifest;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetReadingManifestEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetReadingManifestEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly ReadingManifestDtoFixture _readingManifestDtoFixture = new();
|
||||
private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetReadingManifestEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetReadingManifestEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetReadingManifest_WhenCalledByAuthenticatedUser_ShouldReturnManifestJson()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
ReadingManifestDto manifest = _readingManifestDtoFixture.Create(title: "Test Book");
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/books/{bookId}/reading/manifest", manifest);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-get-reading-manifest?libraryId={libraryId}");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal("Test Book", json.RootElement.GetProperty("data").GetProperty("title").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetReadingManifest_WhenApiReportsNoReaderAvailable_ShouldReturnDistinctErrorCode()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
_apiFactory.ApiClientStub.RegisterGetException($"libraries/{libraryId}/books/{bookId}/reading/manifest", new ApiException(
|
||||
_problemDetailsDtoFixture.Create(detail: "NoReaderAvailable"),
|
||||
HttpStatusCode.NotFound));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-get-reading-manifest?libraryId={libraryId}");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal("NoReaderAvailable", json.RootElement.GetProperty("errorCode").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetReadingManifest_WhenNotAuthenticated_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.GetAsync($"/en-us/library/written-content-library/books-library/books/{Guid.NewGuid()}/api-get-reading-manifest");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
}
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.FileSystemManagement;
|
||||
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.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingResource;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetReadingResourceEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetReadingResourceEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly BlobDataDtoFixture _blobDataDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetReadingResourceEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetReadingResourceEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetReadingResource_WhenCalledByAuthenticatedUser_ShouldReturnResourceBytes()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
string resourceKey = "cover";
|
||||
BlobDataDto blob = _blobDataDtoFixture.Create(contentType: "image/png");
|
||||
_apiFactory.ApiClientStub.RegisterBlobResponse(blob);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-get-reading-resource?resourceKey={resourceKey}");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("image/png"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
byte[] body = await response.Content.ReadAsByteArrayAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal("image/png", response.Content.Headers.ContentType?.MediaType);
|
||||
Assert.Equal(blob.Data, body);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetReadingResource_WhenNotAuthenticated_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.GetAsync($"/en-us/library/written-content-library/books-library/books/{Guid.NewGuid()}/api-get-reading-resource?resourceKey=cover");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
}
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Reading;
|
||||
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.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingSection;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetReadingSectionEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetReadingSectionEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly ReadingSectionDtoFixture _readingSectionDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetReadingSectionEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetReadingSectionEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetReadingSection_WhenCalledByAuthenticatedUser_ShouldReturnSectionJson()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
string locationRef = "chapter-1";
|
||||
ReadingSectionDto section = _readingSectionDtoFixture.Create(locationRef: locationRef, contentHtml: "<p>Content</p>");
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/books/{bookId}/reading/sections/{locationRef}", section);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-get-reading-section?locationRef={locationRef}&libraryId={libraryId}");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(locationRef, json.RootElement.GetProperty("data").GetProperty("locationRef").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetReadingSection_WhenNotAuthenticated_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.GetAsync($"/en-us/library/written-content-library/books-library/books/{Guid.NewGuid()}/api-get-reading-section?locationRef=chapter-1");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
}
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
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 Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.Read;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="ReadViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ReadViewEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly ReadBookViewRequestFixture _readBookViewRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ReadViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public ReadViewEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Read_WhenCalledByAuthenticatedUser_ShouldRenderTheReadView()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
ReadBookViewRequest request = _readBookViewRequestFixture.Create();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/written-content-library/books-library/books/{request.BookId}/read");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Contains("text/html", response.Content.Headers.ContentType?.MediaType, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Read_WhenNotAuthenticated_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.GetAsync($"/en-us/library/written-content-library/books-library/books/{Guid.NewGuid()}/read");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
}
|
||||
}
|
||||
+113
@@ -0,0 +1,113 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.RestoreBook;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.RestoreBook;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="RestoreBookEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RestoreBookEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RestoreBookEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public RestoreBookEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RestoreBook_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldForwardPostAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
_apiFactory.ApiClientStub.RegisterPostSuccess($"libraries/{libraryId}/books/{bookId}/restore");
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage restoreRequest = CreateRestoreRequest(bookId, libraryId);
|
||||
restoreRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(restoreRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.True(json.RootElement.GetProperty("data").GetProperty("isRestored").GetBoolean());
|
||||
Assert.Contains($"libraries/{libraryId}/books/{bookId}/restore", _apiFactory.ApiClientStub.PostRequests.Select(request => request.Endpoint));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RestoreBook_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpRequestMessage restoreRequest = CreateRestoreRequest(bookId, libraryId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(restoreRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Empty(_apiFactory.ApiClientStub.PostRequests);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RestoreBook_WhenNotAuthenticated_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
HttpRequestMessage restoreRequest = CreateRestoreRequest(Guid.NewGuid(), Guid.NewGuid());
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.SendAsync(restoreRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Empty(_apiFactory.ApiClientStub.PostRequests);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the restore request for the book identified by the route, with the owning library passed through the query string.
|
||||
/// </summary>
|
||||
/// <param name="bookId">The route Id of the book to restore.</param>
|
||||
/// <param name="libraryId">The Id of the media library the book belongs to.</param>
|
||||
/// <returns>The configured restore request.</returns>
|
||||
private static HttpRequestMessage CreateRestoreRequest(Guid bookId, Guid libraryId)
|
||||
{
|
||||
HttpRequestMessage restoreRequest = new(HttpMethod.Post, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-restore-book?libraryId={libraryId}")
|
||||
{
|
||||
// The front-end sends the JSON content type even for bodyless POST requests, which triggers the antiforgery validation.
|
||||
Content = new StringContent("{}", Encoding.UTF8, "application/json")
|
||||
};
|
||||
// The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted.
|
||||
restoreRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
restoreRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
return restoreRequest;
|
||||
}
|
||||
}
|
||||
+143
@@ -0,0 +1,143 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books;
|
||||
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 Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.SaveBook;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="SaveBookEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SaveBookEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly UpdateBookRequestFixture _updateBookRequestFixture = new();
|
||||
private readonly BookDetailsDtoFixture _bookDetailsDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SaveBookEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public SaveBookEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveBook_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldForwardUpdateAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
UpdateBookRequest request = _updateBookRequestFixture.Create(id: bookId, libraryId: libraryId);
|
||||
BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create(id: bookId);
|
||||
_apiFactory.ApiClientStub.RegisterPutResponse($"libraries/{libraryId}/books/{bookId}", expectedBook);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage saveRequest = CreateSaveRequest(bookId, request);
|
||||
saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(bookId, json.RootElement.GetProperty("data").GetProperty("id").GetGuid());
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/books/{bookId}" && putRequest.Data is UpdateBookRequest forwarded && forwarded.BookId == bookId.ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveBook_WhenRouteIdDiffersFromBodyId_ShouldForwardTheRouteIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid routeId = Guid.NewGuid();
|
||||
Guid bodyId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
UpdateBookRequest request = _updateBookRequestFixture.Create(id: bodyId, libraryId: libraryId);
|
||||
BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create(id: routeId);
|
||||
_apiFactory.ApiClientStub.RegisterPutResponse($"libraries/{libraryId}/books/{routeId}", expectedBook);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage saveRequest = CreateSaveRequest(routeId, request);
|
||||
saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/books/{routeId}" && putRequest.Data is UpdateBookRequest forwarded && forwarded.BookId == routeId.ToString());
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/books/{bodyId}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveBook_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
UpdateBookRequest request = _updateBookRequestFixture.Create(id: bookId);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage saveRequest = CreateSaveRequest(bookId, request);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{request.LibraryId}/books/{bookId}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveBook_WhenNotAuthenticated_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
HttpRequestMessage saveRequest = CreateSaveRequest(Guid.NewGuid(), _updateBookRequestFixture.Create());
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.SendAsync(saveRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Empty(_apiFactory.ApiClientStub.PutRequests);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the save request that PUTs the given <paramref name="request"/> to the book identified by <paramref name="bookId"/>.
|
||||
/// </summary>
|
||||
/// <param name="bookId">The route Id of the book to save.</param>
|
||||
/// <param name="request">The book data to send.</param>
|
||||
/// <returns>The configured save request.</returns>
|
||||
private static HttpRequestMessage CreateSaveRequest(Guid bookId, UpdateBookRequest request)
|
||||
{
|
||||
HttpRequestMessage saveRequest = new(HttpMethod.Put, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-save-book")
|
||||
{
|
||||
Content = JsonContent.Create(request)
|
||||
};
|
||||
saveRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
saveRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
return saveRequest;
|
||||
}
|
||||
}
|
||||
+176
@@ -0,0 +1,176 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBookCover;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBookCover;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="UpdateBookCoverEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateBookCoverEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new();
|
||||
private readonly UpdateBookCoverDtoFixture _updateBookCoverDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateBookCoverEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public UpdateBookCoverEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateBookCover_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldUploadCoverAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
string expectedPath = "/media/books/cover.png";
|
||||
_apiFactory.ApiClientStub.RegisterPutResponse($"libraries/{libraryId}/books/{bookId}/cover", _updateBookCoverDtoFixture.Create(coverPath: expectedPath));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage uploadRequest = CreateUploadRequest(bookId, libraryId, "cover.png");
|
||||
uploadRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(uploadRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(expectedPath, json.RootElement.GetProperty("data").GetString());
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/books/{bookId}/cover" && putRequest.Data as string == "cover.png");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateBookCover_WhenRouteIdDiffersFromFormIdField_ShouldUseTheRouteId()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid routeId = Guid.NewGuid();
|
||||
Guid formId = Guid.NewGuid();
|
||||
_apiFactory.ApiClientStub.RegisterPutResponse($"libraries/{libraryId}/books/{routeId}/cover", _updateBookCoverDtoFixture.Create(coverPath: "/media/books/cover.png"));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage uploadRequest = CreateUploadRequest(routeId, libraryId, "cover.png");
|
||||
uploadRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
MultipartFormDataContent form = (MultipartFormDataContent)uploadRequest.Content!;
|
||||
form.Add(new StringContent(formId.ToString()), "id");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(uploadRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/books/{routeId}/cover");
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/books/{formId}/cover");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateBookCover_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage uploadRequest = CreateUploadRequest(bookId, libraryId, "cover.png");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(uploadRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/books/{bookId}/cover");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateBookCover_WhenCalledWithoutUploadedFile_ShouldForwardRequestAndReturnFailure()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
ProblemDetailsDto problemDetails = _problemDetailsDtoFixture.Create(title: "General.Validation", detail: "BookCoverCannotBeNull");
|
||||
_apiFactory.ApiClientStub.RegisterPutException($"libraries/{libraryId}/books/{bookId}/cover", new ApiException(problemDetails, HttpStatusCode.UnprocessableEntity, $"libraries/{libraryId}/books/{bookId}/cover"));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
MultipartFormDataContent noFileForm = [];
|
||||
noFileForm.Add(new StringContent("unrelated-field"));
|
||||
HttpRequestMessage uploadRequest = new(HttpMethod.Put, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-update-cover?libraryId={libraryId}")
|
||||
{
|
||||
Content = noFileForm
|
||||
};
|
||||
uploadRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
uploadRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(uploadRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
// The web does not short-circuit the missing file; it forwards the request, and the API reports the missing cover
|
||||
// with the same BookCoverCannotBeNull validation error any other client receives.
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/books/{bookId}/cover" && putRequest.Data == null);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateBookCover_WhenNotAuthenticated_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
HttpRequestMessage uploadRequest = CreateUploadRequest(Guid.NewGuid(), Guid.NewGuid(), "cover.png");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.SendAsync(uploadRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Empty(_apiFactory.ApiClientStub.PutRequests);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the multipart PUT request that uploads a cover to the book identified by <paramref name="bookId"/>.
|
||||
/// </summary>
|
||||
/// <param name="bookId">The route Id of the book whose cover is uploaded.</param>
|
||||
/// <param name="libraryId">The Id of the media library the book belongs to.</param>
|
||||
/// <param name="fileName">The name of the uploaded file.</param>
|
||||
/// <returns>The configured upload request.</returns>
|
||||
private static HttpRequestMessage CreateUploadRequest(Guid bookId, Guid libraryId, string fileName)
|
||||
{
|
||||
MultipartFormDataContent form = [];
|
||||
ByteArrayContent fileContent = new(Encoding.UTF8.GetBytes("fake cover payload"));
|
||||
fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
|
||||
form.Add(fileContent, "cover", fileName);
|
||||
return new HttpRequestMessage(HttpMethod.Put, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-update-cover?libraryId={libraryId}")
|
||||
{
|
||||
Content = form
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user