mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-02 22: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
+52
@@ -0,0 +1,52 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
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.Common.Documentation;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the OpenAPI and Scalar documentation endpoints of the Web application.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class OpenApiEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="OpenApiEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public OpenApiEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task OpenApi_WhenRequested_ShouldServeDocument()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/openapi/v1.json");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.Contains("openapi", content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Scalar_WhenRequested_ShouldServeReferencePage()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/scalar/v1");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType);
|
||||
}
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Configuration;
|
||||
using Lumina.Presentation.Web.Common.HealthChecks;
|
||||
using Microsoft.Extensions.Diagnostics.HealthChecks;
|
||||
using Microsoft.Extensions.Options;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
|
||||
/// <summary>
|
||||
/// API reachability health check that always reports a healthy state.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
internal sealed class HealthyApiReachabilityHealthCheck : ApiReachabilityHealthCheck
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="HealthyApiReachabilityHealthCheck"/> class.
|
||||
/// </summary>
|
||||
/// <param name="httpClientFactory">Injected factory for creating HTTP clients.</param>
|
||||
/// <param name="serverConfigurationOptions">Injected server configuration application settings.</param>
|
||||
public HealthyApiReachabilityHealthCheck(IHttpClientFactory httpClientFactory, IOptionsSnapshot<ServerConfigurationDto> serverConfigurationOptions)
|
||||
: base(httpClientFactory, serverConfigurationOptions)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reports a healthy state without probing the API.
|
||||
/// </summary>
|
||||
public override Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken)
|
||||
{
|
||||
return Task.FromResult(HealthCheckResult.Healthy());
|
||||
}
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.HealthChecks;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Api;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.DependencyInjection.Extensions;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
|
||||
/// <summary>
|
||||
/// Factory for creating the Web application for integration tests, with the remote API client replaced by a configurable stub.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LuminaWebFactory : WebApplicationFactory<Program>, IDisposable
|
||||
{
|
||||
private const string TEST_ENCRYPTION_KEY = "FLYO0QRo6u2VzoFOgNkkEwYNGtqhJ3QGZd7iAHNEJeM=";
|
||||
|
||||
/// <summary>
|
||||
/// Gets the stub used in place of the remote API client.
|
||||
/// </summary>
|
||||
public StubApiHttpClient ApiClientStub { get; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// Gets the stub used in place of the remote streaming API client.
|
||||
/// </summary>
|
||||
public StubStreamingApiHttpClient StreamingApiClientStub { get; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LuminaWebFactory"/> class.
|
||||
/// </summary>
|
||||
public LuminaWebFactory()
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures the web host for the integration tests.
|
||||
/// </summary>
|
||||
/// <param name="builder">The web host builder to configure.</param>
|
||||
protected override void ConfigureWebHost(IWebHostBuilder builder)
|
||||
{
|
||||
builder.ConfigureAppConfiguration((context, config) =>
|
||||
{
|
||||
// Provide the application configuration values that the Web app validates on startup.
|
||||
config.AddInMemoryCollection(initialData: new Dictionary<string, string?>
|
||||
{
|
||||
["EncryptionSettings:SecretKey"] = TEST_ENCRYPTION_KEY,
|
||||
["ServerConfiguration:ApiVersion"] = "1",
|
||||
["ServerConfiguration:BaseAddress"] = "http://localhost",
|
||||
["ServerConfiguration:Port"] = "5214"
|
||||
});
|
||||
});
|
||||
builder.ConfigureServices(services =>
|
||||
{
|
||||
// Remove the typed HTTP client registration, so that the stub can take its place.
|
||||
ServiceDescriptor[] apiClientDescriptors = [.. services.Where(serviceDescriptor => serviceDescriptor.ServiceType == typeof(IApiHttpClient))];
|
||||
foreach (ServiceDescriptor descriptor in apiClientDescriptors)
|
||||
services.Remove(descriptor);
|
||||
services.AddSingleton<IApiHttpClient>(ApiClientStub);
|
||||
|
||||
// Remove the typed streaming HTTP client registration, so that the streaming stub can take its place.
|
||||
ServiceDescriptor[] streamingApiClientDescriptors = [.. services.Where(serviceDescriptor => serviceDescriptor.ServiceType == typeof(IStreamingApiHttpClient))];
|
||||
foreach (ServiceDescriptor descriptor in streamingApiClientDescriptors)
|
||||
services.Remove(descriptor);
|
||||
services.AddSingleton<IStreamingApiHttpClient>(StreamingApiClientStub);
|
||||
|
||||
// The API reachability health check resolves ApiReachabilityHealthCheck from DI when it runs; replace its registration with a healthy subclass, since no real API exists during these tests.
|
||||
services.RemoveAll<ApiReachabilityHealthCheck>();
|
||||
services.AddScoped<ApiReachabilityHealthCheck, HealthyApiReachabilityHealthCheck>();
|
||||
});
|
||||
}
|
||||
}
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Requests.Authorization;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Admin.Authorization.Roles.AddRole;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Authorization;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Authorization;
|
||||
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.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Authorization.Roles.AddRole;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="AddRoleEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddRoleEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly AddRoleRequestFixture _addRoleRequestFixture = new();
|
||||
private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new();
|
||||
private readonly RolePermissionsDtoFixture _rolePermissionsDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddRoleEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public AddRoleEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddRole_WhenCalledByAuthenticatedAdminWithAntiforgeryToken_ShouldForwardRoleAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []);
|
||||
AddRoleRequest request = _addRoleRequestFixture.Create();
|
||||
_apiFactory.ApiClientStub.RegisterPostResponse("auth/roles", _rolePermissionsDtoFixture.Create());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage createRequest = new(HttpMethod.Post, "/en-us/admin/api-create-role")
|
||||
{
|
||||
Content = JsonContent.Create(request)
|
||||
};
|
||||
createRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
createRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
createRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(createRequest);
|
||||
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 == "auth/roles");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddRole_WhenCalledByNonAdminUser_ShouldRedirectToAccessDenied()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []);
|
||||
AddRoleRequest request = _addRoleRequestFixture.Create();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage createRequest = new(HttpMethod.Post, "/en-us/admin/api-create-role")
|
||||
{
|
||||
Content = JsonContent.Create(request)
|
||||
};
|
||||
createRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
createRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
createRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(createRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Contains("access-denied", response.Headers.Location!.ToString());
|
||||
}
|
||||
}
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Admin.Authorization.Roles.DeleteRole;
|
||||
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.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Authorization.Roles.DeleteRole;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="DeleteRoleEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteRoleEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteRoleEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public DeleteRoleEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteRole_WhenCalledByAuthenticatedAdminWithAntiforgeryToken_ShouldForwardDeleteAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []);
|
||||
Guid roleId = Guid.NewGuid();
|
||||
string expectedEndpoint = $"auth/roles/{roleId}";
|
||||
_apiFactory.ApiClientStub.RegisterDeleteSuccess(expectedEndpoint);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage deleteRequest = new(HttpMethod.Delete, $"/en-us/admin/api-delete-role/{roleId}")
|
||||
{
|
||||
Content = new StringContent("{}", Encoding.UTF8, "application/json")
|
||||
};
|
||||
deleteRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
deleteRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
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 == expectedEndpoint);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteRole_WhenCalledByNonAdminUser_ShouldRedirectToAccessDenied()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []);
|
||||
Guid roleId = Guid.NewGuid();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage deleteRequest = new(HttpMethod.Delete, $"/en-us/admin/api-delete-role/{roleId}")
|
||||
{
|
||||
Content = new StringContent("{}", Encoding.UTF8, "application/json")
|
||||
};
|
||||
deleteRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
deleteRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
deleteRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Contains("access-denied", response.Headers.Location!.ToString());
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Authorization;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Admin.Authorization.Roles.GetRolePermissions;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Authorization;
|
||||
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.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Authorization.Roles.GetRolePermissions;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetRolePermissionsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetRolePermissionsEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new();
|
||||
private readonly RolePermissionsDtoFixture _rolePermissionsDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetRolePermissionsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetRolePermissionsEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRolePermissions_WhenCalledByAuthenticatedAdmin_ShouldReturnRolePermissionsJson()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []);
|
||||
Guid roleId = Guid.NewGuid();
|
||||
RolePermissionsDto expectedResponse = _rolePermissionsDtoFixture.Create();
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"auth/roles/{roleId}/permissions", expectedResponse);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/admin/api-get-permissions-by-role-id/{roleId}");
|
||||
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.Permissions.Length, json.RootElement.GetProperty("data").GetProperty("permissions").GetArrayLength());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRolePermissions_WhenCalledByNonAdminUser_ShouldRedirectToAccessDenied()
|
||||
{
|
||||
// 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("/en-us/admin/api-get-permissions-by-role-id/" + Guid.NewGuid());
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Contains("access-denied", response.Headers.Location!.ToString());
|
||||
}
|
||||
}
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Authorization;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Admin.Authorization.Roles.GetRoles;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Authorization;
|
||||
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.Admin.Authorization.Roles.GetRoles;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetRolesEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetRolesEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new();
|
||||
private readonly RoleDtoFixture _roleDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetRolesEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetRolesEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRoles_WhenCalledByAdminUser_ShouldReturnRolesJson()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []);
|
||||
RoleDto[] expectedRoles = [_roleDtoFixture.Create(id: Guid.NewGuid(), roleName: "Admin"), _roleDtoFixture.Create(id: Guid.NewGuid(), roleName: "User")];
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse("auth/roles", expectedRoles);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/api-get-roles");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(2, json.RootElement.GetProperty("data").GetArrayLength());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRoles_WhenCalledByNonAdminUser_ShouldRedirectToAccessDenied()
|
||||
{
|
||||
// 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("/en-us/admin/api-get-roles");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Contains("access-denied", response.Headers.Location!.ToString());
|
||||
}
|
||||
}
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Requests.Authorization;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Admin.Authorization.Roles.UpdateRole;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Authorization;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Authorization;
|
||||
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.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Authorization.Roles.UpdateRole;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="UpdateRoleEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateRoleEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new();
|
||||
private readonly RolePermissionsDtoFixture _rolePermissionsDtoFixture = new();
|
||||
private readonly UpdateRoleRequestFixture _updateRoleRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateRoleEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public UpdateRoleEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateRole_WhenCalledByAuthenticatedAdminWithAntiforgeryToken_ShouldForwardUpdateAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []);
|
||||
UpdateRoleRequest request = _updateRoleRequestFixture.Create();
|
||||
_apiFactory.ApiClientStub.RegisterPutResponse("auth/roles", _rolePermissionsDtoFixture.Create());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/admin/api-update-role")
|
||||
{
|
||||
Content = JsonContent.Create(request)
|
||||
};
|
||||
updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
updateRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest);
|
||||
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.PutRequests, putRequest => putRequest.Endpoint == "auth/roles");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateRole_WhenCalledByNonAdminUser_ShouldRedirectToAccessDenied()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []);
|
||||
UpdateRoleRequest request = _updateRoleRequestFixture.Create();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/admin/api-update-role")
|
||||
{
|
||||
Content = JsonContent.Create(request)
|
||||
};
|
||||
updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
updateRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Contains("access-denied", response.Headers.Location!.ToString());
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Authorization;
|
||||
using Lumina.Presentation.Web.Common.DTO.UsersManagement;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Admin.ManagePermissions;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Authorization;
|
||||
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.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.ManagePermissions;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="ManagePermissionsViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ManagePermissionsViewEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new();
|
||||
private readonly PermissionDtoFixture _permissionDtoFixture = new();
|
||||
private readonly RoleDtoFixture _roleDtoFixture = new();
|
||||
private readonly UserDtoFixture _userDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ManagePermissionsViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public ManagePermissionsViewEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ManagePermissions_WhenCalledByAuthenticatedAdmin_ShouldRenderPermissionsManagementPage()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []);
|
||||
UserDto[] expectedUsers = [.. _userDtoFixture.CreateMany()];
|
||||
RoleDto[] expectedRoles = [.. _roleDtoFixture.CreateMany()];
|
||||
PermissionDto[] expectedPermissions = [.. _permissionDtoFixture.CreateMany()];
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse("auth/users", expectedUsers);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse("auth/roles", expectedRoles);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse("auth/permissions", expectedPermissions);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/manage-permissions");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ManagePermissions_WhenCalledByNonAdminUser_ShouldRedirectToAccessDenied()
|
||||
{
|
||||
// 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("/en-us/admin/manage-permissions");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Contains("access-denied", response.Headers.Location!.ToString());
|
||||
}
|
||||
}
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Authorization;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Admin.ManageRoles;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Authorization;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using Polly.CircuitBreaker;
|
||||
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.Admin.ManageRoles;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="ManageRolesViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ManageRolesViewEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new();
|
||||
private readonly PermissionDtoFixture _permissionDtoFixture = new();
|
||||
private readonly RoleDtoFixture _roleDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ManageRolesViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public ManageRolesViewEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ManageRoles_WhenCalledByAuthenticatedAdmin_ShouldRenderRolesManagementPage()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []);
|
||||
RoleDto[] expectedRoles = [.. _roleDtoFixture.CreateMany()];
|
||||
PermissionDto[] expectedPermissions = [.. _permissionDtoFixture.CreateMany()];
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse("auth/roles", expectedRoles);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse("auth/permissions", expectedPermissions);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/manage-roles");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ManageRoles_WhenCalledByNonAdminUser_ShouldRedirectToAccessDenied()
|
||||
{
|
||||
// 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("/en-us/admin/manage-roles");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Contains("access-denied", response.Headers.Location!.ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ManageRoles_WhenTheApiIsUnreachableDuringAuthorization_ShouldRenderThePage()
|
||||
{
|
||||
// Arrange
|
||||
// The policy handler runs under real endpoint routing, where the authorization resource is the endpoint, not the HttpContext.
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.AuthorizationException = new BrokenCircuitException();
|
||||
RoleDto[] expectedRoles = [.. _roleDtoFixture.CreateMany()];
|
||||
PermissionDto[] expectedPermissions = [.. _permissionDtoFixture.CreateMany()];
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse("auth/roles", expectedRoles);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse("auth/permissions", expectedPermissions);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/manage-roles");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.Contains("data-server-unreachable-banner", content);
|
||||
}
|
||||
}
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Scheduling;
|
||||
using Lumina.Presentation.Web.Common.Requests.Scheduling;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.AddScheduledJob;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Scheduling;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Scheduling;
|
||||
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.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Scheduler.AddScheduledJob;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="AddScheduledJobEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddScheduledJobEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly AddScheduledJobRequestFixture _addScheduledJobRequestFixture = new();
|
||||
private readonly ScheduledJobDtoFixture _scheduledJobDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddScheduledJobEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public AddScheduledJobEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddScheduledJob_WhenCalledByAuthenticatedAdminWithAntiforgeryToken_ShouldAddScheduledJobAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AddScheduledJobRequest request = _addScheduledJobRequestFixture.Create();
|
||||
_apiFactory.ApiClientStub.RegisterPostResponse("scheduled-jobs", _scheduledJobDtoFixture.Create(name: request.Name));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage addRequest = new(HttpMethod.Post, "/en-us/admin/api-scheduled-jobs/add")
|
||||
{
|
||||
Content = JsonContent.Create(request)
|
||||
};
|
||||
addRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
addRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
addRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(addRequest);
|
||||
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 == "scheduled-jobs");
|
||||
}
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Requests.Scheduling;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.FireScheduledJob;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Scheduling;
|
||||
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.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Scheduler.FireScheduledJob;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="FireScheduledJobEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class FireScheduledJobEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly FireScheduledJobRequestFixture _fireScheduledJobRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="FireScheduledJobEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public FireScheduledJobEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task FireScheduledJob_WhenCalledByAuthenticatedAdminWithAntiforgeryToken_ShouldFireScheduledJobAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
FireScheduledJobRequest request = _fireScheduledJobRequestFixture.Create();
|
||||
string expectedEndpoint = $"scheduled-jobs/{request.ScheduledJobId}/fire";
|
||||
_apiFactory.ApiClientStub.RegisterPutPayload<FireScheduledJobRequest>(expectedEndpoint);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage fireRequest = new(HttpMethod.Put, $"/en-us/admin/api-scheduled-jobs/{request.ScheduledJobId}/fire")
|
||||
{
|
||||
Content = JsonContent.Create(request)
|
||||
};
|
||||
fireRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
fireRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
fireRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(fireRequest);
|
||||
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.PutRequests, putRequest => putRequest.Endpoint == expectedEndpoint);
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Scheduling;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.GetScheduledJobHistory;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Scheduling;
|
||||
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.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Scheduler.GetScheduledJobHistory;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetScheduledJobHistoryEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetScheduledJobHistoryEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly ScheduledJobExecutionDtoFixture _scheduledJobExecutionDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetScheduledJobHistoryEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetScheduledJobHistoryEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetScheduledJobHistory_WhenCalledByAuthenticatedAdmin_ShouldReturnExecutionHistoryFromApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
ScheduledJobExecutionDto[] expectedExecutions = [.. _scheduledJobExecutionDtoFixture.CreateMany(2)];
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse("scheduled-jobs/history", expectedExecutions);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/admin/api-scheduled-jobs/history");
|
||||
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(expectedExecutions.Length, json.RootElement.GetProperty("data").GetArrayLength());
|
||||
Assert.Contains(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == "scheduled-jobs/history");
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Scheduling;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.GetScheduledJobs;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Scheduling;
|
||||
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.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Scheduler.GetScheduledJobs;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetScheduledJobsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetScheduledJobsEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly ScheduledJobDtoFixture _scheduledJobDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetScheduledJobsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetScheduledJobsEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetScheduledJobs_WhenCalledByAuthenticatedAdmin_ShouldReturnScheduledJobsFromApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
ScheduledJobDto[] expectedJobs = [.. _scheduledJobDtoFixture.CreateMany(2)];
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse("scheduled-jobs", expectedJobs);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/admin/api-scheduled-jobs");
|
||||
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(expectedJobs.Length, json.RootElement.GetProperty("data").GetArrayLength());
|
||||
Assert.Contains(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == "scheduled-jobs");
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Scheduling;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.GetSchedulerDisplayPreferences;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Scheduling;
|
||||
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.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Scheduler.GetSchedulerDisplayPreferences;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetSchedulerDisplayPreferencesEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetSchedulerDisplayPreferencesEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly SchedulerDisplayPreferencesDtoFixture _schedulerDisplayPreferencesDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetSchedulerDisplayPreferencesEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetSchedulerDisplayPreferencesEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetSchedulerDisplayPreferences_WhenCalledByAuthenticatedAdmin_ShouldReturnDisplayPreferencesFromApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
SchedulerDisplayPreferencesDto expectedPreferences = _schedulerDisplayPreferencesDtoFixture.Create();
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse("scheduled-jobs/display-preferences", expectedPreferences);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/admin/api-scheduled-jobs/display-preferences");
|
||||
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(expectedPreferences.UserId, json.RootElement.GetProperty("data").GetProperty("userId").GetGuid());
|
||||
Assert.Contains(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == "scheduled-jobs/display-preferences");
|
||||
}
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Requests.Scheduling;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.RemoveScheduledJob;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Scheduling;
|
||||
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.Admin.Scheduler.RemoveScheduledJob;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="RemoveScheduledJobEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RemoveScheduledJobEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly RemoveScheduledJobRequestFixture _removeScheduledJobRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RemoveScheduledJobEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public RemoveScheduledJobEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveScheduledJob_WhenCalledByAuthenticatedAdminWithAntiforgeryToken_ShouldRemoveScheduledJobAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
RemoveScheduledJobRequest request = _removeScheduledJobRequestFixture.Create();
|
||||
string expectedEndpoint = $"scheduled-jobs/{request.ScheduledJobId}";
|
||||
_apiFactory.ApiClientStub.RegisterDeleteSuccess(expectedEndpoint);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage removeRequest = new(HttpMethod.Delete, $"/en-us/admin/api-scheduled-jobs/{request.ScheduledJobId}")
|
||||
{
|
||||
Content = new StringContent("{}", Encoding.UTF8, "application/json")
|
||||
};
|
||||
removeRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
removeRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
removeRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(removeRequest);
|
||||
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 == expectedEndpoint);
|
||||
}
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler;
|
||||
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.Admin.Scheduler;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="SchedulerIndexViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SchedulerIndexViewEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SchedulerIndexViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public SchedulerIndexViewEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SchedulerIndex_WhenCalledByAuthenticatedAdmin_ShouldRenderSchedulerPage()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/scheduled-jobs");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SchedulerIndex_WhenCalledByNonAdminUser_ShouldRedirectToAccessDenied()
|
||||
{
|
||||
// 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("/en-us/admin/scheduled-jobs");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Contains("access-denied", response.Headers.Location!.ToString());
|
||||
}
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Requests.Scheduling;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.StartScheduledJob;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Scheduling;
|
||||
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.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Scheduler.StartScheduledJob;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="StartScheduledJobEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class StartScheduledJobEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly StartScheduledJobRequestFixture _startScheduledJobRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="StartScheduledJobEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public StartScheduledJobEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartScheduledJob_WhenCalledByAuthenticatedAdminWithAntiforgeryToken_ShouldStartScheduledJobAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
StartScheduledJobRequest request = _startScheduledJobRequestFixture.Create();
|
||||
string expectedEndpoint = $"scheduled-jobs/{request.ScheduledJobId}/start";
|
||||
_apiFactory.ApiClientStub.RegisterPutPayload<StartScheduledJobRequest>(expectedEndpoint);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage startRequest = new(HttpMethod.Put, $"/en-us/admin/api-scheduled-jobs/{request.ScheduledJobId}/start")
|
||||
{
|
||||
Content = JsonContent.Create(request)
|
||||
};
|
||||
startRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
startRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
startRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(startRequest);
|
||||
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.PutRequests, putRequest => putRequest.Endpoint == expectedEndpoint);
|
||||
}
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Requests.Scheduling;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.StopScheduledJob;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Scheduling;
|
||||
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.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Scheduler.StopScheduledJob;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="StopScheduledJobEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class StopScheduledJobEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly StopScheduledJobRequestFixture _stopScheduledJobRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="StopScheduledJobEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public StopScheduledJobEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StopScheduledJob_WhenCalledByAuthenticatedAdminWithAntiforgeryToken_ShouldStopScheduledJobAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
StopScheduledJobRequest request = _stopScheduledJobRequestFixture.Create();
|
||||
string expectedEndpoint = $"scheduled-jobs/{request.ScheduledJobId}/stop";
|
||||
_apiFactory.ApiClientStub.RegisterPutPayload<StopScheduledJobRequest>(expectedEndpoint);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage stopRequest = new(HttpMethod.Put, $"/en-us/admin/api-scheduled-jobs/{request.ScheduledJobId}/stop")
|
||||
{
|
||||
Content = JsonContent.Create(request)
|
||||
};
|
||||
stopRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
stopRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
stopRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(stopRequest);
|
||||
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.PutRequests, putRequest => putRequest.Endpoint == expectedEndpoint);
|
||||
}
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Requests.Scheduling;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.UpdateSchedulerDisplayPreferences;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Scheduling;
|
||||
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.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Scheduler.UpdateSchedulerDisplayPreferences;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="UpdateSchedulerDisplayPreferencesEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateSchedulerDisplayPreferencesEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly UpdateSchedulerDisplayPreferencesRequestFixture _updateSchedulerDisplayPreferencesRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateSchedulerDisplayPreferencesEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public UpdateSchedulerDisplayPreferencesEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateSchedulerDisplayPreferences_WhenCalledByAuthenticatedAdminWithAntiforgeryToken_ShouldUpdateDisplayPreferencesAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
UpdateSchedulerDisplayPreferencesRequest request = _updateSchedulerDisplayPreferencesRequestFixture.Create();
|
||||
_apiFactory.ApiClientStub.RegisterPutPayload<UpdateSchedulerDisplayPreferencesRequest>("scheduled-jobs/display-preferences");
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/admin/api-scheduled-jobs/display-preferences")
|
||||
{
|
||||
Content = JsonContent.Create(request)
|
||||
};
|
||||
updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
updateRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest);
|
||||
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.PutRequests, putRequest => putRequest.Endpoint == "scheduled-jobs/display-preferences");
|
||||
}
|
||||
}
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.DeleteTheme;
|
||||
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.Admin.Themes.DeleteTheme;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="DeleteThemeEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteThemeEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteThemeEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public DeleteThemeEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteTheme_WhenCalledByAuthenticatedAdminWithAntiforgeryToken_ShouldDeleteThemeAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
const string THEME_ID = "test-theme";
|
||||
_apiFactory.ApiClientStub.RegisterDeleteSuccess($"themes/{THEME_ID}");
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage deleteRequest = new(HttpMethod.Delete, $"/en-us/admin/themes/api-delete-theme/{THEME_ID}")
|
||||
{
|
||||
Content = new StringContent("{}", Encoding.UTF8, "application/json")
|
||||
};
|
||||
deleteRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
deleteRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
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 == $"themes/{THEME_ID}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteTheme_WhenCalledWithEmptyThemeId_ShouldReturnBadRequest()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage deleteRequest = new(HttpMethod.Delete, "/en-us/admin/themes/api-delete-theme/%20")
|
||||
{
|
||||
Content = new StringContent("{}", Encoding.UTF8, "application/json")
|
||||
};
|
||||
deleteRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
deleteRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
deleteRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Empty(_apiFactory.ApiClientStub.DeleteEndpointsCalled);
|
||||
}
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.DownloadTheme;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement;
|
||||
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.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Themes.DownloadTheme;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="DownloadThemeEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DownloadThemeEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly BlobDataDtoFixture _blobDataDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DownloadThemeEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public DownloadThemeEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DownloadTheme_WhenCalledByAuthenticatedAdmin_ShouldReturnThemeArchive()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
byte[] expectedBytes = [0x50, 0x4B, 0x03, 0x04, 0x01, 0x02];
|
||||
_apiFactory.ApiClientStub.RegisterBlobResponse(_blobDataDtoFixture.Create(data: expectedBytes, contentType: "application/zip"));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage downloadRequest = new(HttpMethod.Get, "/en-us/admin/themes/api-download-theme/test-theme");
|
||||
downloadRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(downloadRequest);
|
||||
byte[] content = await response.Content.ReadAsByteArrayAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal("application/zip", response.Content.Headers.ContentType!.MediaType);
|
||||
Assert.Equal(expectedBytes, content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DownloadTheme_WhenCalledWithEmptyThemeId_ShouldReturnBadRequest()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage downloadRequest = new(HttpMethod.Get, "/en-us/admin/themes/api-download-theme/%20");
|
||||
downloadRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(downloadRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
}
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Themes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.GetThemes;
|
||||
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.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Themes.GetThemes;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetThemesEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetThemesEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly ThemeResponseDtoFixture _themeResponseDtoFixture = new();
|
||||
private readonly ThemeSettingsResponseDtoFixture _themeSettingsResponseDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetThemesEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetThemesEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetThemes_WhenCalledByAuthenticatedAdmin_ShouldReturnThemesFromApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
ThemeResponseDto[] expectedThemes = [.. _themeResponseDtoFixture.CreateMany()];
|
||||
ThemeResponseDto currentTheme = _themeResponseDtoFixture.Create(themeId: "current-theme");
|
||||
ThemeSettingsResponseDto expectedSettings = _themeSettingsResponseDtoFixture.Create();
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse("themes", expectedThemes);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse("themes/current", currentTheme);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse("themes/settings", expectedSettings);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/admin/themes/api-get-themes");
|
||||
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(expectedThemes.Length, data.GetProperty("themes").GetArrayLength());
|
||||
Assert.Equal("current-theme", data.GetProperty("currentThemeId").GetString());
|
||||
Assert.Equal(expectedSettings.MaxArchiveBytes, data.GetProperty("maxArchiveBytes").GetInt64());
|
||||
Assert.Contains(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == "themes");
|
||||
Assert.Contains(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == "themes/current");
|
||||
Assert.Contains(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == "themes/settings");
|
||||
}
|
||||
}
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Themes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.InstallTheme;
|
||||
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.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Themes.InstallTheme;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="InstallThemeEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class InstallThemeEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly ThemeResponseDtoFixture _themeResponseDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="InstallThemeEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public InstallThemeEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InstallTheme_WhenCalledByAuthenticatedAdminWithAntiforgeryToken_ShouldForwardUploadAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
string fileName = "theme.zip";
|
||||
_apiFactory.ApiClientStub.RegisterPostResponse("themes", _themeResponseDtoFixture.Create());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage installRequest = new(HttpMethod.Post, "/en-us/admin/themes/api-install-theme")
|
||||
{
|
||||
Content = CreateMultipartContent(fileName)
|
||||
};
|
||||
installRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
installRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(installRequest);
|
||||
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 == "themes" && postRequest.Data as string == fileName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InstallTheme_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage installRequest = new(HttpMethod.Post, "/en-us/admin/themes/api-install-theme")
|
||||
{
|
||||
Content = CreateMultipartContent("theme.zip")
|
||||
};
|
||||
installRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(installRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "themes");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds a multipart form content carrying a single file part.
|
||||
/// </summary>
|
||||
/// <param name="fileName">The name of the uploaded file.</param>
|
||||
/// <returns>The multipart form content.</returns>
|
||||
private static MultipartFormDataContent CreateMultipartContent(string fileName)
|
||||
{
|
||||
MultipartFormDataContent form = [];
|
||||
ByteArrayContent fileContent = new([0x50, 0x4B, 0x03, 0x04]);
|
||||
fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
|
||||
form.Add(fileContent, "archive", fileName);
|
||||
return form;
|
||||
}
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.RestoreTheme;
|
||||
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.Admin.Themes.RestoreTheme;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="RestoreThemeEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RestoreThemeEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RestoreThemeEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public RestoreThemeEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RestoreTheme_WhenCalledByAuthenticatedAdminWithAntiforgeryToken_ShouldRestoreThemeAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
const string THEME_ID = "test-theme";
|
||||
_apiFactory.ApiClientStub.RegisterPostSuccess($"themes/{THEME_ID}/restore");
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage restoreRequest = new(HttpMethod.Post, $"/en-us/admin/themes/api-restore-theme/{THEME_ID}")
|
||||
{
|
||||
Content = new StringContent("{}", Encoding.UTF8, "application/json")
|
||||
};
|
||||
restoreRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
restoreRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
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.Contains(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == $"themes/{THEME_ID}/restore");
|
||||
}
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Requests.Themes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.SetCurrentTheme;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Themes;
|
||||
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.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Themes.SetCurrentTheme;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="SetCurrentThemeEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SetCurrentThemeEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly SetCurrentThemeRequestFixture _setCurrentThemeRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SetCurrentThemeEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public SetCurrentThemeEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetCurrentTheme_WhenCalledByAuthenticatedAdminWithAntiforgeryToken_ShouldSetCurrentThemeAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
const string THEME_ID = "test-theme";
|
||||
_apiFactory.ApiClientStub.RegisterPutPayload<SetCurrentThemeRequest>("themes/current");
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage setCurrentThemeRequest = new(HttpMethod.Put, "/en-us/admin/themes/api-set-current-theme")
|
||||
{
|
||||
Content = JsonContent.Create(_setCurrentThemeRequestFixture.Create(themeId: THEME_ID))
|
||||
};
|
||||
setCurrentThemeRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
setCurrentThemeRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
setCurrentThemeRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(setCurrentThemeRequest);
|
||||
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.PutRequests, putRequest => putRequest.Endpoint == "themes/current");
|
||||
}
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Themes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes;
|
||||
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.Admin.Themes;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="ThemesIndexViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ThemesIndexViewEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly ThemeResponseDtoFixture _themeResponseDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ThemesIndexViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public ThemesIndexViewEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ThemesIndex_WhenCalledByAuthenticatedAdmin_ShouldRenderThemesManagementPage()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
ThemeResponseDto[] expectedThemes = [.. _themeResponseDtoFixture.CreateMany()];
|
||||
ThemeResponseDto currentTheme = _themeResponseDtoFixture.Create(themeId: "current-theme");
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse("themes", expectedThemes);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse("themes/current", currentTheme);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/manage-themes");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType);
|
||||
Assert.Contains(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == "themes");
|
||||
Assert.Contains(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == "themes/current");
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Authorization;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Admin.UsersManagement.Authorization.GetUserPermissions;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Authorization;
|
||||
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.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.UsersManagement.Authorization.GetUserPermissions;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetUserPermissionsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetUserPermissionsEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new();
|
||||
private readonly PermissionDtoFixture _permissionDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetUserPermissionsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetUserPermissionsEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserPermissions_WhenCalledByAuthenticatedAdmin_ShouldReturnUserPermissionsJson()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []);
|
||||
Guid userId = Guid.NewGuid();
|
||||
PermissionDto[] expectedPermissions = [.. _permissionDtoFixture.CreateMany()];
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"auth/users/{userId}/permissions", expectedPermissions);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/admin/api-get-permissions-by-user-id/{userId}");
|
||||
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(expectedPermissions.Length, json.RootElement.GetProperty("data").GetArrayLength());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserPermissions_WhenCalledByNonAdminUser_ShouldRedirectToAccessDenied()
|
||||
{
|
||||
// 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("/en-us/admin/api-get-permissions-by-user-id/" + Guid.NewGuid());
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Contains("access-denied", response.Headers.Location!.ToString());
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Authorization;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Admin.UsersManagement.Authorization.GetUserRole;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Authorization;
|
||||
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.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.UsersManagement.Authorization.GetUserRole;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetUserRoleEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetUserRoleEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new();
|
||||
private readonly RoleDtoFixture _roleDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetUserRoleEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetUserRoleEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserRole_WhenCalledByAuthenticatedAdmin_ShouldReturnUserRoleJson()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []);
|
||||
Guid userId = Guid.NewGuid();
|
||||
RoleDto expectedRole = _roleDtoFixture.Create();
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"auth/users/{userId}/role", expectedRole);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/admin/api-get-role-by-user-id/{userId}");
|
||||
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(expectedRole.RoleName, json.RootElement.GetProperty("data").GetProperty("roleName").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserRole_WhenCalledByNonAdminUser_ShouldRedirectToAccessDenied()
|
||||
{
|
||||
// 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("/en-us/admin/api-get-role-by-user-id/" + Guid.NewGuid());
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Contains("access-denied", response.Headers.Location!.ToString());
|
||||
}
|
||||
}
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Requests.Authorization;
|
||||
using Lumina.Presentation.Web.Common.Responses.Authorization;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Admin.UsersManagement.Authorization.UpdateUserRoleAndPermissions;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Authorization;
|
||||
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.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.UsersManagement.Authorization.UpdateUserRoleAndPermissions;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="UpdateUserRoleAndPermissionsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateUserRoleAndPermissionsEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new();
|
||||
private readonly UpdateUserRoleAndPermissionsRequestFixture _updateUserRoleAndPermissionsRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateUserRoleAndPermissionsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public UpdateUserRoleAndPermissionsEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateUserRoleAndPermissions_WhenCalledByAuthenticatedAdminWithAntiforgeryToken_ShouldForwardUpdateAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []);
|
||||
UpdateUserRoleAndPermissionsRequest request = _updateUserRoleAndPermissionsRequestFixture.Create();
|
||||
string expectedEndpoint = $"auth/users/{request.UserId}/role-and-permissions";
|
||||
GetAuthorizationResponse expectedResponse = _getAuthorizationResponseFixture.Create(userId: request.UserId);
|
||||
_apiFactory.ApiClientStub.RegisterPutResponse(expectedEndpoint, expectedResponse);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/admin/api-update-user-authorization")
|
||||
{
|
||||
Content = JsonContent.Create(request)
|
||||
};
|
||||
updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
updateRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest);
|
||||
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.PutRequests, putRequest => putRequest.Endpoint == expectedEndpoint);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateUserRoleAndPermissions_WhenCalledByNonAdminUser_ShouldRedirectToAccessDenied()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []);
|
||||
UpdateUserRoleAndPermissionsRequest request = _updateUserRoleAndPermissionsRequestFixture.Create();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/admin/api-update-user-authorization")
|
||||
{
|
||||
Content = JsonContent.Create(request)
|
||||
};
|
||||
updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
updateRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Contains("access-denied", response.Headers.Location!.ToString());
|
||||
}
|
||||
}
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Favorites;
|
||||
using Lumina.Presentation.Web.Common.Enums.Favorites;
|
||||
using Lumina.Presentation.Web.Common.Requests.Favorites;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Favorites.AddFavorite;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Favorites;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.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.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Favorites.AddFavorite;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="AddFavoriteEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddFavoriteEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string WEB_ROUTE = "/en-us/favorites/api-add-favorite";
|
||||
private const string UPSTREAM_ENDPOINT = "users/me/favorites";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly FavoriteDtoFixture _favoriteDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddFavoriteEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public AddFavoriteEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddFavorite_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldForwardTheFavoriteAndReturnIt()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
FavoriteDto expectedFavorite = _favoriteDtoFixture.Create(
|
||||
mediaKind: FavoriteMediaKind.MusicTrack,
|
||||
mediaItemId: mediaItemId);
|
||||
_apiFactory.ApiClientStub.RegisterPostResponse(UPSTREAM_ENDPOINT, expectedFavorite);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage addRequest = CreateAddRequest(FavoriteMediaKind.MusicTrack, mediaItemId, webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(addRequest);
|
||||
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(expectedFavorite.Id, data.GetProperty("id").GetGuid());
|
||||
Assert.Equal(nameof(FavoriteMediaKind.MusicTrack), data.GetProperty("mediaKind").GetString());
|
||||
Assert.Equal(mediaItemId, data.GetProperty("mediaItemId").GetGuid());
|
||||
Assert.Equal(expectedFavorite.FavoritedOnUtc, data.GetProperty("favoritedOnUtc").GetDateTime());
|
||||
List<(string Endpoint, object? Data)> addRequests = GetAddRequests();
|
||||
(string Endpoint, object? Data) addRequestCall = Assert.Single(addRequests);
|
||||
Assert.Equal(UPSTREAM_ENDPOINT, addRequestCall.Endpoint);
|
||||
AddFavoriteRequest forwardedPayload = Assert.IsType<AddFavoriteRequest>(addRequestCall.Data);
|
||||
Assert.Equal(FavoriteMediaKind.MusicTrack, forwardedPayload.MediaKind);
|
||||
Assert.Equal(mediaItemId, forwardedPayload.MediaItemId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the add favorite requests that were sent upstream, excluding the login request performed to authenticate the test client.
|
||||
/// </summary>
|
||||
/// <returns>The list of upstream add favorite requests that were sent.</returns>
|
||||
private List<(string Endpoint, object? Data)> GetAddRequests()
|
||||
{
|
||||
return [.. _apiFactory.ApiClientStub.PostRequests
|
||||
.Where(postRequest => postRequest.Endpoint == UPSTREAM_ENDPOINT)];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the add favorite request for the specified media item.
|
||||
/// </summary>
|
||||
/// <param name="mediaKind">The kind of the media item to favorite.</param>
|
||||
/// <param name="mediaItemId">The Id of the media item to favorite.</param>
|
||||
/// <param name="antiforgeryToken">The antiforgery token to include in the request.</param>
|
||||
/// <returns>The configured add favorite request.</returns>
|
||||
private static HttpRequestMessage CreateAddRequest(FavoriteMediaKind mediaKind, Guid mediaItemId, string antiforgeryToken)
|
||||
{
|
||||
string payload = $"{{\"mediaKind\":\"{mediaKind}\",\"mediaItemId\":\"{mediaItemId}\"}}";
|
||||
HttpRequestMessage addRequest = new(HttpMethod.Post, WEB_ROUTE)
|
||||
{
|
||||
Content = new StringContent(payload, Encoding.UTF8, "application/json")
|
||||
};
|
||||
// The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted.
|
||||
addRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
addRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
addRequest.Headers.Add("RequestVerificationToken", antiforgeryToken);
|
||||
return addRequest;
|
||||
}
|
||||
|
||||
/// <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);
|
||||
}
|
||||
}
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Favorites;
|
||||
using Lumina.Presentation.Web.Common.Enums.Favorites;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Favorites.GetFavoriteStatus;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Favorites;
|
||||
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.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Favorites.GetFavoriteStatus;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetFavoriteStatusEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetFavoriteStatusEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string WEB_ROUTE = "/en-us/favorites/api-get-favorite-status";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly FavoriteStatusDtoFixture _favoriteStatusDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetFavoriteStatusEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetFavoriteStatusEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavoriteStatus_WhenCalledWithMediaKindAndIds_ShouldForwardThemAndSurfaceTheFavoritedIds()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
List<Guid> mediaItemIds = [Guid.NewGuid(), Guid.NewGuid()];
|
||||
string expectedUpstreamEndpoint = $"users/me/favorites/status?mediaKind=MusicTrack&mediaItemIds={mediaItemIds[0]}&mediaItemIds={mediaItemIds[1]}";
|
||||
FavoriteStatusDto expectedStatus = _favoriteStatusDtoFixture.Create(favoritedMediaItemIds: [mediaItemIds[1]]);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(expectedUpstreamEndpoint, expectedStatus);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync(
|
||||
$"{WEB_ROUTE}?mediaKind=MusicTrack&mediaItemIds={mediaItemIds[0]}&mediaItemIds={mediaItemIds[1]}");
|
||||
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());
|
||||
List<Guid> favoritedIds = [.. json.RootElement.GetProperty("data").GetProperty("favoritedMediaItemIds").EnumerateArray().Select(element => element.GetGuid())];
|
||||
Assert.Equal(expectedStatus.FavoritedMediaItemIds, favoritedIds);
|
||||
Assert.Equal([expectedUpstreamEndpoint], GetFavoriteStatusEndpointCalls());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavoriteStatus_WhenMediaKindAndIdsAreOmitted_ShouldForwardTheBareStatusRoute()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
const string EXPECTED_UPSTREAM_ENDPOINT = "users/me/favorites/status";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(EXPECTED_UPSTREAM_ENDPOINT, _favoriteStatusDtoFixture.Create());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync(WEB_ROUTE);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal([EXPECTED_UPSTREAM_ENDPOINT], GetFavoriteStatusEndpointCalls());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the favorite status endpoints that were called upstream, excluding the requests made to authenticate the test client.
|
||||
/// </summary>
|
||||
/// <returns>The list of upstream favorite status endpoints that were called.</returns>
|
||||
private List<string> GetFavoriteStatusEndpointCalls()
|
||||
{
|
||||
return [.. _apiFactory.ApiClientStub.GetEndpointsCalled
|
||||
.Where(endpoint => endpoint.StartsWith("users/me/favorites/status", 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);
|
||||
}
|
||||
}
|
||||
+185
@@ -0,0 +1,185 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Common.DTO.Favorites;
|
||||
using Lumina.Presentation.Web.Common.Enums.Favorites;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Favorites.GetFavorites;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Favorites;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.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.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Favorites.GetFavorites;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetFavoritesEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetFavoritesEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string WEB_ROUTE = "/en-us/favorites/api-get-favorites";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly PaginatedDtoFixture<FavoriteItemDto> _paginatedDtoFixture = new();
|
||||
private readonly FavoriteItemDtoFixture _favoriteItemDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetFavoritesEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetFavoritesEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavorites_WhenCalledByAuthenticatedUser_ShouldSurfaceThePaginatedFavoritesUnchanged()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
FavoriteItemDto expectedItem = _favoriteItemDtoFixture.Create(
|
||||
mediaKind: FavoriteMediaKind.MusicTrack,
|
||||
isAvailable: true,
|
||||
title: "Time",
|
||||
collectionTitle: "The Dark Side of the Moon",
|
||||
creatorName: "Pink Floyd",
|
||||
coverPath: "covers/dark-side-of-the-moon.jpg");
|
||||
PaginatedDto<FavoriteItemDto> expectedPage = _paginatedDtoFixture.Create(
|
||||
data: [expectedItem],
|
||||
currentPage: 1,
|
||||
perPage: 200,
|
||||
count: 1,
|
||||
numberOfPages: 1);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse("users/me/favorites?currentPage=1&perPage=200", expectedPage);
|
||||
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(1, data.GetProperty("currentPage").GetInt32());
|
||||
Assert.Equal(200, data.GetProperty("perPage").GetInt32());
|
||||
Assert.Equal(1, data.GetProperty("count").GetInt32());
|
||||
Assert.Equal(1, data.GetProperty("numberOfPages").GetInt32());
|
||||
JsonElement item = Assert.Single(data.GetProperty("data").EnumerateArray());
|
||||
Assert.Equal(nameof(FavoriteMediaKind.MusicTrack), item.GetProperty("mediaKind").GetString());
|
||||
Assert.Equal(expectedItem.MediaItemId, item.GetProperty("mediaItemId").GetGuid());
|
||||
Assert.True(item.GetProperty("isAvailable").GetBoolean());
|
||||
Assert.Equal(expectedItem.LibraryId, item.GetProperty("libraryId").GetGuid());
|
||||
Assert.Equal(expectedItem.Title, item.GetProperty("title").GetString());
|
||||
Assert.Equal(expectedItem.CollectionId, item.GetProperty("collectionId").GetGuid());
|
||||
Assert.Equal(expectedItem.CollectionTitle, item.GetProperty("collectionTitle").GetString());
|
||||
Assert.Equal(expectedItem.CreatorId, item.GetProperty("creatorId").GetGuid());
|
||||
Assert.Equal(expectedItem.CreatorName, item.GetProperty("creatorName").GetString());
|
||||
Assert.Equal(expectedItem.CoverPath, item.GetProperty("coverPath").GetString());
|
||||
Assert.Equal(["users/me/favorites?currentPage=1&perPage=200"], GetFavoritesEndpointCalls());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("", "users/me/favorites?currentPage=1&perPage=200")] // Neither the page nor the size is supplied.
|
||||
[InlineData("?currentPage=3", "users/me/favorites?currentPage=3&perPage=200")] // Only the page is supplied.
|
||||
[InlineData("?perPage=25", "users/me/favorites?currentPage=1&perPage=25")] // Only the size is supplied.
|
||||
[InlineData("?currentPage=2&perPage=50", "users/me/favorites?currentPage=2&perPage=50")] // Both the page and the size are supplied.
|
||||
public async Task GetFavorites_WhenCalledWithPagination_ShouldForwardTheDocumentedUpstreamUrl(string queryString, string expectedUpstreamEndpoint)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(expectedUpstreamEndpoint, _paginatedDtoFixture.Create());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"{WEB_ROUTE}{queryString}");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal([expectedUpstreamEndpoint], GetFavoritesEndpointCalls());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavorites_WhenMediaKindIsSupplied_ShouldAppendItToTheUpstreamUrl()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
const string EXPECTED_UPSTREAM_ENDPOINT = "users/me/favorites?currentPage=1&perPage=200&mediaKind=MusicTrack";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(EXPECTED_UPSTREAM_ENDPOINT, _paginatedDtoFixture.Create());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"{WEB_ROUTE}?mediaKind=MusicTrack");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal([EXPECTED_UPSTREAM_ENDPOINT], GetFavoritesEndpointCalls());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavorites_WhenMediaItemIsUnavailable_ShouldPassTheEmptyDisplayDataThroughUnchanged()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
FavoriteItemDto unavailableItem = _favoriteItemDtoFixture.Create(
|
||||
mediaKind: FavoriteMediaKind.Book,
|
||||
isAvailable: false,
|
||||
libraryId: Guid.Empty,
|
||||
title: string.Empty,
|
||||
collectionId: Guid.Empty,
|
||||
collectionTitle: string.Empty,
|
||||
creatorId: Guid.Empty,
|
||||
creatorName: string.Empty,
|
||||
includeCoverPath: false);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(
|
||||
"users/me/favorites?currentPage=1&perPage=200",
|
||||
_paginatedDtoFixture.Create(data: [unavailableItem], currentPage: 1, perPage: 200, count: 1, numberOfPages: 1));
|
||||
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);
|
||||
JsonElement item = Assert.Single(json.RootElement.GetProperty("data").GetProperty("data").EnumerateArray());
|
||||
Assert.False(item.GetProperty("isAvailable").GetBoolean());
|
||||
Assert.Equal(Guid.Empty, item.GetProperty("libraryId").GetGuid());
|
||||
Assert.Equal(string.Empty, item.GetProperty("title").GetString());
|
||||
Assert.Equal(Guid.Empty, item.GetProperty("collectionId").GetGuid());
|
||||
Assert.Equal(string.Empty, item.GetProperty("collectionTitle").GetString());
|
||||
Assert.Equal(Guid.Empty, item.GetProperty("creatorId").GetGuid());
|
||||
Assert.Equal(string.Empty, item.GetProperty("creatorName").GetString());
|
||||
Assert.Equal(JsonValueKind.Null, item.GetProperty("coverPath").ValueKind);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the favorites endpoints that were called upstream, excluding the requests made to authenticate the test client.
|
||||
/// </summary>
|
||||
/// <returns>The list of upstream favorites endpoints that were called.</returns>
|
||||
private List<string> GetFavoritesEndpointCalls()
|
||||
{
|
||||
return [.. _apiFactory.ApiClientStub.GetEndpointsCalled
|
||||
.Where(endpoint => endpoint.StartsWith("users/me/favorites", 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);
|
||||
}
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Favorites.Index;
|
||||
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.Favorites.Index;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="FavoritesIndexViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class FavoritesIndexViewEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string WEB_ROUTE = "/en-us/favorites";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="FavoritesIndexViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public FavoritesIndexViewEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task FavoritesIndexView_WhenCalledByAuthenticatedUser_ShouldRenderTheFavoritesPage()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
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("favorites-container", content, StringComparison.Ordinal);
|
||||
Assert.Contains("favorites-kind-filter", content, StringComparison.Ordinal);
|
||||
Assert.Contains("no-favorites", content, StringComparison.Ordinal);
|
||||
Assert.True(response.Headers.CacheControl?.Private);
|
||||
Assert.True(response.Headers.CacheControl?.NoStore);
|
||||
Assert.Contains("no-store", string.Join(", ", response.Headers.GetValues("Cache-Control")), StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Contains("Cookie", response.Headers.Vary);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task FavoritesIndexView_WhenCalledByAuthenticatedUser_ShouldRenderTheAntiforgeryTokenAndTheLocalizedStrings()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
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.Contains("__RequestVerificationToken", content, StringComparison.Ordinal);
|
||||
Assert.Contains("Favorites", content, StringComparison.Ordinal);
|
||||
Assert.Contains("You have no favorites yet.", content, StringComparison.Ordinal);
|
||||
Assert.Contains("Load more", content, 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);
|
||||
}
|
||||
}
|
||||
+143
@@ -0,0 +1,143 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Enums.Favorites;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Favorites.RemoveFavorite;
|
||||
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.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Favorites.RemoveFavorite;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="RemoveFavoriteEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RemoveFavoriteEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string ZERO_GUID = "00000000-0000-0000-0000-000000000000";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RemoveFavoriteEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public RemoveFavoriteEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveFavorite_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldForwardTheNormalizedDeleteAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
string expectedUpstreamEndpoint = $"users/me/favorites/MusicTrack/{mediaItemId}";
|
||||
_apiFactory.ApiClientStub.RegisterDeleteSuccess(expectedUpstreamEndpoint);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage removeRequest = CreateRemoveRequest(nameof(FavoriteMediaKind.MusicTrack), mediaItemId.ToString(), webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(removeRequest);
|
||||
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([expectedUpstreamEndpoint], GetRemoveEndpointCalls());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveFavorite_WhenMediaKindAndIdAreCasedDifferently_ShouldForwardTheCanonicalValuesOnly()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid mediaItemId = Guid.Parse("ABCDEFAB-CDEF-ABCD-EFAB-CDEFABCDEFAB");
|
||||
string expectedUpstreamEndpoint = $"users/me/favorites/MusicTrack/{mediaItemId}";
|
||||
_apiFactory.ApiClientStub.RegisterDeleteSuccess(expectedUpstreamEndpoint);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage removeRequest = CreateRemoveRequest("musictrack", mediaItemId.ToString().ToUpperInvariant(), webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(removeRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
List<string> removeEndpoints = GetRemoveEndpointCalls();
|
||||
Assert.Equal([expectedUpstreamEndpoint], removeEndpoints);
|
||||
Assert.DoesNotContain(mediaItemId.ToString().ToUpperInvariant(), string.Join(",", removeEndpoints), StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveFavorite_WhenRouteValuesAreCrafted_ShouldForwardTheSanitizedPlaceholders()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
string expectedUpstreamEndpoint = $"users/me/favorites/Invalid/{ZERO_GUID}";
|
||||
_apiFactory.ApiClientStub.RegisterDeleteSuccess(expectedUpstreamEndpoint);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage removeRequest = CreateRemoveRequest("notamediakind", "not-a-guid", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(removeRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
List<string> removeEndpoints = GetRemoveEndpointCalls();
|
||||
Assert.Equal([expectedUpstreamEndpoint], removeEndpoints);
|
||||
Assert.DoesNotContain("notamediakind", string.Join(",", removeEndpoints), StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("not-a-guid", string.Join(",", removeEndpoints), StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the remove favorite endpoints that were called upstream, excluding the requests made to authenticate the test client.
|
||||
/// </summary>
|
||||
/// <returns>The list of upstream remove favorite endpoints that were called.</returns>
|
||||
private List<string> GetRemoveEndpointCalls()
|
||||
{
|
||||
return [.. _apiFactory.ApiClientStub.DeleteEndpointsCalled
|
||||
.Where(endpoint => endpoint.StartsWith("users/me/favorites", StringComparison.Ordinal))];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the remove favorite request for the specified route values.
|
||||
/// </summary>
|
||||
/// <param name="mediaKind">The value of the media kind route segment.</param>
|
||||
/// <param name="mediaItemId">The value of the media item identifier route segment.</param>
|
||||
/// <param name="antiforgeryToken">The antiforgery token to include in the request.</param>
|
||||
/// <returns>The configured remove favorite request.</returns>
|
||||
private static HttpRequestMessage CreateRemoveRequest(string mediaKind, string mediaItemId, string antiforgeryToken)
|
||||
{
|
||||
HttpRequestMessage removeRequest = new(HttpMethod.Delete, $"/en-us/favorites/{Uri.EscapeDataString(mediaKind)}/{Uri.EscapeDataString(mediaItemId)}/api-remove-favorite")
|
||||
{
|
||||
// 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.
|
||||
removeRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
removeRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
removeRequest.Headers.Add("RequestVerificationToken", antiforgeryToken);
|
||||
return removeRequest;
|
||||
}
|
||||
|
||||
/// <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);
|
||||
}
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.FileSystemManagement;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Directories.GetDirectories;
|
||||
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.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.FileSystemManagement.Directories.GetDirectories;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetDirectoriesEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetDirectoriesEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly DirectoryDtoFixture _directoryDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetDirectoriesEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetDirectoriesEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetDirectories_WhenCalledByAuthenticatedUser_ShouldReturnDirectoriesFromApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
string path = @"C:\Users\test";
|
||||
DirectoryDto[] expectedDirectories = [_directoryDtoFixture.Create(path: path, name: "test", isHidden: true)];
|
||||
string expectedEndpoint = $"directories/get-directories?path={Uri.EscapeDataString(path)}&shouldIncludeHiddenElements=True";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, expectedDirectories);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/directories/api-get-directories?path={Uri.EscapeDataString(path)}&shouldIncludeHiddenElements=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(expectedDirectories.Length, json.RootElement.GetProperty("data").GetArrayLength());
|
||||
Assert.True(json.RootElement.GetProperty("data")[0].GetProperty("isHidden").GetBoolean());
|
||||
Assert.Contains(expectedEndpoint, _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.FileSystemManagement;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Drives.GetDrives;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement;
|
||||
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.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.FileSystemManagement.Drives.GetDrives;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetDrivesEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetDrivesEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly FileSystemTreeNodeDtoFixture _fileSystemTreeNodeDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetDrivesEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetDrivesEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetDrives_WhenCalledByAuthenticatedUser_ShouldReturnDrivesFromApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
FileSystemTreeNodeDto[] expectedDrives = [_fileSystemTreeNodeDtoFixture.Create(path: "C:\\", name: "C:")];
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse("drives/get-drives", expectedDrives);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, "/drives/api-get-drives");
|
||||
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(expectedDrives.Length, json.RootElement.GetProperty("data").GetProperty("drives").GetArrayLength());
|
||||
Assert.Contains("drives/get-drives", _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Enums.FileSystem;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.FileSystem.GetType;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement;
|
||||
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.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.FileSystemManagement.FileSystem.GetType;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetTypeEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetTypeEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly FileSystemTypeDtoFixture _fileSystemTypeDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetTypeEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetTypeEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetType_WhenCalledByAuthenticatedUser_ShouldReturnFileSystemTypeFromApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse("file-system/get-type", _fileSystemTypeDtoFixture.Create(platformType: PlatformType.Windows));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, "/file-system/api-get-type");
|
||||
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(nameof(PlatformType.Windows), json.RootElement.GetProperty("data").GetProperty("platformType").GetString());
|
||||
Assert.Contains("file-system/get-type", _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.FileSystemManagement;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Files.GetFiles;
|
||||
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.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.FileSystemManagement.Files.GetFiles;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetFilesEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetFilesEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly FileDtoFixture _fileDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetFilesEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetFilesEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFiles_WhenCalledByAuthenticatedUser_ShouldReturnFilesFromApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
string path = @"C:\Users\test";
|
||||
FileDto[] expectedFiles = [_fileDtoFixture.Create(path: path, name: "book.pdf", isHidden: true)];
|
||||
string expectedEndpoint = $"files/get-files?path={Uri.EscapeDataString(path)}&shouldIncludeHiddenElements=True";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, expectedFiles);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/files/api-get-files?path={Uri.EscapeDataString(path)}&shouldIncludeHiddenElements=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(expectedFiles.Length, json.RootElement.GetProperty("data").GetArrayLength());
|
||||
Assert.True(json.RootElement.GetProperty("data")[0].GetProperty("isHidden").GetBoolean());
|
||||
Assert.Contains(expectedEndpoint, _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.FileSystemManagement;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Files.GetTreeFiles;
|
||||
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.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.FileSystemManagement.Files.GetTreeFiles;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetTreeFilesEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetTreeFilesEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly FileSystemTreeNodeDtoFixture _fileSystemTreeNodeDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetTreeFilesEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetTreeFilesEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTreeFiles_WhenCalledByAuthenticatedUser_ShouldReturnFileSystemTreeFromApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
string path = @"C:\Users\test";
|
||||
FileSystemTreeNodeDto[] expectedNodes = [_fileSystemTreeNodeDtoFixture.Create(path: path, name: "test", isHidden: true)];
|
||||
string expectedEndpoint = $"files/get-tree-files?path={Uri.EscapeDataString(path)}&shouldIncludeHiddenElements=True";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, expectedNodes);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/files/api-get-tree-files?path={Uri.EscapeDataString(path)}&shouldIncludeHiddenElements=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(expectedNodes.Length, json.RootElement.GetProperty("data").GetArrayLength());
|
||||
Assert.True(json.RootElement.GetProperty("data")[0].GetProperty("isHidden").GetBoolean());
|
||||
Assert.Contains(expectedEndpoint, _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Path.CheckPathExists;
|
||||
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.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.FileSystemManagement.Path.CheckPathExists;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="CheckPathExistsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class CheckPathExistsEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly PathExistsDtoFixture _pathExistsDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CheckPathExistsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public CheckPathExistsEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CheckPathExists_WhenCalledByAuthenticatedUser_ShouldReturnExistenceFromApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
string path = @"C:\Users\test";
|
||||
string expectedEndpoint = $"path/check-path-exists?path={Uri.EscapeDataString(path)}&shouldIncludeHiddenElements=True";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, _pathExistsDtoFixture.Create(exists: true));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/path/api-check-path-exists?path={Uri.EscapeDataString(path)}&shouldIncludeHiddenElements=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.True(json.RootElement.GetProperty("data").GetProperty("exists").GetBoolean());
|
||||
Assert.Contains(expectedEndpoint, _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.FileSystemManagement;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Path.GetPathParent;
|
||||
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.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.FileSystemManagement.Path.GetPathParent;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetPathParentEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetPathParentEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly PathSegmentDtoFixture _pathSegmentDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPathParentEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetPathParentEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPathParent_WhenCalledByAuthenticatedUser_ShouldReturnPathSegmentsFromApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
string path = @"C:\Users\test";
|
||||
PathSegmentDto[] expectedSegments = [_pathSegmentDtoFixture.Create(path: @"C:\Users")];
|
||||
string expectedEndpoint = $"path/get-path-parent?path={Uri.EscapeDataString(path)}";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, expectedSegments);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/path/api-get-path-parent?path={Uri.EscapeDataString(path)}");
|
||||
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(expectedSegments.Length, json.RootElement.GetProperty("data").GetProperty("pathSegments").GetArrayLength());
|
||||
Assert.Contains(expectedEndpoint, _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Path.GetPathRoot;
|
||||
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.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.FileSystemManagement.Path.GetPathRoot;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetPathRootEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetPathRootEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly PathSegmentDtoFixture _pathSegmentDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPathRootEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetPathRootEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPathRoot_WhenCalledByAuthenticatedUser_ShouldReturnPathRootFromApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
string path = @"C:\Users\test";
|
||||
string expectedEndpoint = $"path/get-path-root?path={Uri.EscapeDataString(path)}";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, _pathSegmentDtoFixture.Create(path: @"C:\"));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/path/api-get-path-root?path={Uri.EscapeDataString(path)}");
|
||||
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(@"C:\", json.RootElement.GetProperty("data").GetProperty("root").GetProperty("path").GetString());
|
||||
Assert.Contains(expectedEndpoint, _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Path.GetPathSeparator;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement;
|
||||
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.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.FileSystemManagement.Path.GetPathSeparator;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetPathSeparatorEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetPathSeparatorEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly PathSeparatorDtoFixture _pathSeparatorDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPathSeparatorEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetPathSeparatorEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPathSeparator_WhenCalledByAuthenticatedUser_ShouldReturnPathSeparatorFromApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
string expectedSeparator = "\\";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse("path/get-path-separator", _pathSeparatorDtoFixture.Create(separator: expectedSeparator));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, "/path/api-get-path-separator");
|
||||
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(expectedSeparator, json.RootElement.GetProperty("data").GetProperty("pathSeparator").GetString());
|
||||
Assert.Contains("path/get-path-separator", _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
}
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.FileSystemManagement;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Path.SplitPath;
|
||||
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.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.FileSystemManagement.Path.SplitPath;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="SplitPathEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SplitPathEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly PathSegmentDtoFixture _pathSegmentDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SplitPathEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public SplitPathEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SplitPath_WhenCalledByAuthenticatedUser_ShouldReturnPathSegmentsFromApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
string path = @"C:\Users\test";
|
||||
PathSegmentDto[] expectedSegments =
|
||||
[
|
||||
_pathSegmentDtoFixture.Create(path: @"C:\"),
|
||||
_pathSegmentDtoFixture.Create(path: "Users"),
|
||||
_pathSegmentDtoFixture.Create(path: "test")
|
||||
];
|
||||
string expectedEndpoint = $"path/split?path={Uri.EscapeDataString(path)}";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, expectedSegments);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/path/api-split?path={Uri.EscapeDataString(path)}");
|
||||
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(expectedSegments.Length, json.RootElement.GetProperty("data").GetProperty("pathSegments").GetArrayLength());
|
||||
Assert.Contains(expectedEndpoint, _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Path.ValidatePath;
|
||||
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.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.FileSystemManagement.Path.ValidatePath;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="ValidatePathEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ValidatePathEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly PathValidDtoFixture _pathValidDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ValidatePathEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public ValidatePathEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ValidatePath_WhenCalledByAuthenticatedUser_ShouldReturnValidityFromApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
string path = @"C:\Users\test";
|
||||
string expectedEndpoint = $"path/validate?path={Uri.EscapeDataString(path)}";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, _pathValidDtoFixture.Create(isValid: true));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/path/api-validate?path={Uri.EscapeDataString(path)}");
|
||||
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.True(json.RootElement.GetProperty("data").GetProperty("isValid").GetBoolean());
|
||||
Assert.Contains(expectedEndpoint, _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Home;
|
||||
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.Home;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="HomeErrorEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class HomeErrorEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="HomeErrorEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public HomeErrorEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HomeError_WhenCalledByAuthenticatedUser_ShouldRenderErrorPage()
|
||||
{
|
||||
// Arrange
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/error");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.Contains("Navigation failed!", content);
|
||||
Assert.Contains("data-server-unreachable-banner", content);
|
||||
}
|
||||
}
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Home;
|
||||
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.Home;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="HomeIndexEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class HomeIndexEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="HomeIndexEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public HomeIndexEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Home_WhenCalledWithoutCulture_ShouldRedirectToDefaultCulture()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.GetAsync("/");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Equal("/en-us/", response.Headers.Location!.ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Home_WhenCalledWithoutAuthentication_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.GetAsync("/en-us");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Home_WhenCalledByAuthenticatedUser_ShouldReturnHomePage()
|
||||
{
|
||||
// Arrange
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync("/en-us");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.Contains("html", content);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("/de-de")] // German culture.
|
||||
[InlineData("/fr-fr")] // French culture.
|
||||
[InlineData("/ja-jp")] // Japanese culture.
|
||||
public async Task Home_WhenCalledByAuthenticatedUserWithLocalizedCulture_ShouldReturnHomePage(string culturePath)
|
||||
{
|
||||
// Arrange
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync(culturePath);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
}
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Home;
|
||||
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.Home;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="HomeNotFoundViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class HomeNotFoundViewEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="HomeNotFoundViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public HomeNotFoundViewEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HomeNotFoundView_WhenCalledByAuthenticatedUser_ShouldRenderNotFoundPage()
|
||||
{
|
||||
// Arrange
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/not-found");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType);
|
||||
}
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Home;
|
||||
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.Home;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="HomePrivacyEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class HomePrivacyEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="HomePrivacyEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public HomePrivacyEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HomePrivacy_WhenCalledByAuthenticatedUser_ShouldRenderPrivacyPage()
|
||||
{
|
||||
// Arrange
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/privacy");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.Contains("Privacy Policy", content);
|
||||
}
|
||||
}
|
||||
+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)}";
|
||||
}
|
||||
}
|
||||
Loaded 100 of 6450 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user