mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 18:57:24 +00:00
test: adds unit, integration and security test projects for the web project
This commit is contained in:
1 parent
7b56033a15
commit
7ad7ad308e
70 files changed
+4993
No files matched your search
@@ -1,3 +1,4 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 17
|
||||
VisualStudioVersion = 17.0.31903.59
|
||||
@@ -223,6 +224,14 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Lumina.Presentation.Api.Fix
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Lumina.Domain.SharedKernel.Fixtures", "..\tests\Common\Lumina.Domain.SharedKernel.Fixtures\Lumina.Domain.SharedKernel.Fixtures.csproj", "{A6BC3F8B-CAB8-4F3B-BD89-B7428697DE61}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Presentation.Web.Fixtures", "..\tests\Common\Lumina.Presentation.Web.Fixtures\Lumina.Presentation.Web.Fixtures.csproj", "{52245330-641B-4E14-823A-10B3D9105D58}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Presentation.Web.UnitTests", "..\tests\UnitTests\Lumina.Presentation.Web.UnitTests\Lumina.Presentation.Web.UnitTests.csproj", "{697F6057-DBDC-40B9-A7E5-02F295BC18B3}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Presentation.Web.IntegrationTests", "..\tests\IntegrationTests\Lumina.Presentation.Web.IntegrationTests\Lumina.Presentation.Web.IntegrationTests.csproj", "{4BE18EDC-02ED-47E2-A23A-3F6650ADAF0A}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Presentation.Web.SecurityTests", "..\tests\SecurityTests\Lumina.Presentation.Web.SecurityTests\Lumina.Presentation.Web.SecurityTests.csproj", "{3FE25467-CBC6-438F-BB96-6601AF56E937}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
@@ -517,6 +526,54 @@ Global
|
||||
{A6BC3F8B-CAB8-4F3B-BD89-B7428697DE61}.Release|x64.Build.0 = Release|Any CPU
|
||||
{A6BC3F8B-CAB8-4F3B-BD89-B7428697DE61}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{A6BC3F8B-CAB8-4F3B-BD89-B7428697DE61}.Release|x86.Build.0 = Release|Any CPU
|
||||
{52245330-641B-4E14-823A-10B3D9105D58}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{52245330-641B-4E14-823A-10B3D9105D58}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{52245330-641B-4E14-823A-10B3D9105D58}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{52245330-641B-4E14-823A-10B3D9105D58}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{52245330-641B-4E14-823A-10B3D9105D58}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{52245330-641B-4E14-823A-10B3D9105D58}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{52245330-641B-4E14-823A-10B3D9105D58}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{52245330-641B-4E14-823A-10B3D9105D58}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{52245330-641B-4E14-823A-10B3D9105D58}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{52245330-641B-4E14-823A-10B3D9105D58}.Release|x64.Build.0 = Release|Any CPU
|
||||
{52245330-641B-4E14-823A-10B3D9105D58}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{52245330-641B-4E14-823A-10B3D9105D58}.Release|x86.Build.0 = Release|Any CPU
|
||||
{697F6057-DBDC-40B9-A7E5-02F295BC18B3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{697F6057-DBDC-40B9-A7E5-02F295BC18B3}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{697F6057-DBDC-40B9-A7E5-02F295BC18B3}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{697F6057-DBDC-40B9-A7E5-02F295BC18B3}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{697F6057-DBDC-40B9-A7E5-02F295BC18B3}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{697F6057-DBDC-40B9-A7E5-02F295BC18B3}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{697F6057-DBDC-40B9-A7E5-02F295BC18B3}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{697F6057-DBDC-40B9-A7E5-02F295BC18B3}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{697F6057-DBDC-40B9-A7E5-02F295BC18B3}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{697F6057-DBDC-40B9-A7E5-02F295BC18B3}.Release|x64.Build.0 = Release|Any CPU
|
||||
{697F6057-DBDC-40B9-A7E5-02F295BC18B3}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{697F6057-DBDC-40B9-A7E5-02F295BC18B3}.Release|x86.Build.0 = Release|Any CPU
|
||||
{4BE18EDC-02ED-47E2-A23A-3F6650ADAF0A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{4BE18EDC-02ED-47E2-A23A-3F6650ADAF0A}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{4BE18EDC-02ED-47E2-A23A-3F6650ADAF0A}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{4BE18EDC-02ED-47E2-A23A-3F6650ADAF0A}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{4BE18EDC-02ED-47E2-A23A-3F6650ADAF0A}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{4BE18EDC-02ED-47E2-A23A-3F6650ADAF0A}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{4BE18EDC-02ED-47E2-A23A-3F6650ADAF0A}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{4BE18EDC-02ED-47E2-A23A-3F6650ADAF0A}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{4BE18EDC-02ED-47E2-A23A-3F6650ADAF0A}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{4BE18EDC-02ED-47E2-A23A-3F6650ADAF0A}.Release|x64.Build.0 = Release|Any CPU
|
||||
{4BE18EDC-02ED-47E2-A23A-3F6650ADAF0A}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{4BE18EDC-02ED-47E2-A23A-3F6650ADAF0A}.Release|x86.Build.0 = Release|Any CPU
|
||||
{3FE25467-CBC6-438F-BB96-6601AF56E937}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{3FE25467-CBC6-438F-BB96-6601AF56E937}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{3FE25467-CBC6-438F-BB96-6601AF56E937}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{3FE25467-CBC6-438F-BB96-6601AF56E937}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{3FE25467-CBC6-438F-BB96-6601AF56E937}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{3FE25467-CBC6-438F-BB96-6601AF56E937}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{3FE25467-CBC6-438F-BB96-6601AF56E937}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{3FE25467-CBC6-438F-BB96-6601AF56E937}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{3FE25467-CBC6-438F-BB96-6601AF56E937}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{3FE25467-CBC6-438F-BB96-6601AF56E937}.Release|x64.Build.0 = Release|Any CPU
|
||||
{3FE25467-CBC6-438F-BB96-6601AF56E937}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{3FE25467-CBC6-438F-BB96-6601AF56E937}.Release|x86.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
@@ -570,6 +627,10 @@ Global
|
||||
{7C2AB7E7-F58B-4F96-BDFB-05E403BD999B} = {7E8A2D6B-3F4C-4E5F-9A6B-1C2D3E4F5A6B}
|
||||
{4E7353D5-5F1C-43A1-B792-6CD1D5DBDB91} = {7E8A2D6B-3F4C-4E5F-9A6B-1C2D3E4F5A6B}
|
||||
{A6BC3F8B-CAB8-4F3B-BD89-B7428697DE61} = {7E8A2D6B-3F4C-4E5F-9A6B-1C2D3E4F5A6B}
|
||||
{52245330-641B-4E14-823A-10B3D9105D58} = {7E8A2D6B-3F4C-4E5F-9A6B-1C2D3E4F5A6B}
|
||||
{697F6057-DBDC-40B9-A7E5-02F295BC18B3} = {53B1231B-37F5-44BA-80D5-DBA979775F5C}
|
||||
{4BE18EDC-02ED-47E2-A23A-3F6650ADAF0A} = {3F057926-562F-4EF4-BFC0-EE62372D4551}
|
||||
{3FE25467-CBC6-438F-BB96-6601AF56E937} = {8B06B1D2-80B9-490C-9A36-C7748F58B705}
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {4A55A28E-C657-4A0B-95EA-2931AE66004E}
|
||||
|
||||
@@ -0,0 +1,255 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.FileSystemManagement;
|
||||
using Lumina.Presentation.Web.Common.Enums.Authorization;
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Lumina.Presentation.Web.Common.Responses.Authorization;
|
||||
using Lumina.Presentation.Web.Common.Responses.UsersManagement;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.Api;
|
||||
|
||||
/// <summary>
|
||||
/// Test double for the <see cref="IApiHttpClient"/> interface, allowing integration and security tests to stub the
|
||||
/// remote API responses without hosting a real backend.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class StubApiHttpClient : IApiHttpClient
|
||||
{
|
||||
private readonly Dictionary<string, Func<object>> _getResponseFactories = [];
|
||||
private readonly Dictionary<string, Func<object, object>> _postResponseFactories = [];
|
||||
private readonly Dictionary<string, Func<object, object>> _putResponseFactories = [];
|
||||
private readonly HashSet<string> _deleteSuccessEndpoints = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets the authorization response returned for the <c>auth/get-authorization</c> endpoint.
|
||||
/// </summary>
|
||||
public GetAuthorizationResponse AuthorizationResponse { get; set; } = new(Guid.NewGuid(), "Admin", Enum.GetValues<AuthorizationPermission>());
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the initialization response returned for the <c>initialization</c> endpoint.
|
||||
/// </summary>
|
||||
public InitializationResponse InitializationResponse { get; set; } = new() { IsInitialized = true };
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the login response returned for the <c>auth/login</c> endpoint.
|
||||
/// </summary>
|
||||
public LoginResponse LoginResponse { get; set; } = new(Guid.NewGuid(), "testuser", "test_jwt_token", false);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the list of GET endpoints that were requested.
|
||||
/// </summary>
|
||||
public List<string> GetEndpointsCalled { get; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets the list of POST requests that were sent, with their payloads.
|
||||
/// </summary>
|
||||
public List<(string Endpoint, object? Data)> PostRequests { get; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets the list of PUT requests that were sent, with their payloads.
|
||||
/// </summary>
|
||||
public List<(string Endpoint, object? Data)> PutRequests { get; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets the list of DELETE endpoints that were requested.
|
||||
/// </summary>
|
||||
public List<string> DeleteEndpointsCalled { get; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Registers the response returned when the specified GET endpoint is called.
|
||||
/// </summary>
|
||||
/// <typeparam name="TResponse">The type of the response.</typeparam>
|
||||
/// <param name="endpoint">The API endpoint for which to register the response.</param>
|
||||
/// <param name="response">The response to return.</param>
|
||||
public void RegisterGetResponse<TResponse>(string endpoint, TResponse response) where TResponse : class
|
||||
{
|
||||
_getResponseFactories[endpoint] = () => response;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers the response factory invoked when the specified GET endpoint is called.
|
||||
/// </summary>
|
||||
/// <param name="endpoint">The API endpoint for which to register the response factory.</param>
|
||||
/// <param name="responseFactory">The factory that produces the response.</param>
|
||||
public void RegisterGetResponseFactory(string endpoint, Func<object> responseFactory)
|
||||
{
|
||||
_getResponseFactories[endpoint] = responseFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers the response returned when the specified POST endpoint is called.
|
||||
/// </summary>
|
||||
/// <typeparam name="TResponse">The type of the response.</typeparam>
|
||||
/// <param name="endpoint">The API endpoint for which to register the response.</param>
|
||||
/// <param name="response">The response to return.</param>
|
||||
public void RegisterPostResponse<TResponse>(string endpoint, TResponse response) where TResponse : class
|
||||
{
|
||||
_postResponseFactories[endpoint] = _ => response;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers the response factory invoked when the specified POST endpoint is called.
|
||||
/// </summary>
|
||||
/// <param name="endpoint">The API endpoint for which to register the response factory.</param>
|
||||
/// <param name="responseFactory">The factory that produces the response from the request payload.</param>
|
||||
public void RegisterPostResponseFactory(string endpoint, Func<object, object> responseFactory)
|
||||
{
|
||||
_postResponseFactories[endpoint] = responseFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers the exception thrown when the specified POST endpoint is called.
|
||||
/// </summary>
|
||||
/// <param name="endpoint">The API endpoint for which to register the exception.</param>
|
||||
/// <param name="exception">The exception to throw.</param>
|
||||
public void RegisterPostException(string endpoint, ApiException exception)
|
||||
{
|
||||
_postResponseFactories[endpoint] = _ => throw exception;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers the exception thrown when the specified GET endpoint is called.
|
||||
/// </summary>
|
||||
/// <param name="endpoint">The API endpoint for which to register the exception.</param>
|
||||
/// <param name="exception">The exception to throw.</param>
|
||||
public void RegisterGetException(string endpoint, ApiException exception)
|
||||
{
|
||||
_getResponseFactories[endpoint] = () => throw exception;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers the response returned when the specified PUT endpoint is called.
|
||||
/// </summary>
|
||||
/// <typeparam name="TResponse">The type of the response.</typeparam>
|
||||
/// <param name="endpoint">The API endpoint for which to register the response.</param>
|
||||
/// <param name="response">The response to return.</param>
|
||||
public void RegisterPutResponse<TResponse>(string endpoint, TResponse response) where TResponse : class
|
||||
{
|
||||
_putResponseFactories[endpoint] = _ => response;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers the specified DELETE endpoint as succeeding.
|
||||
/// </summary>
|
||||
/// <param name="endpoint">The API endpoint for which to register success.</param>
|
||||
public void RegisterDeleteSuccess(string endpoint)
|
||||
{
|
||||
_deleteSuccessEndpoints.Add(endpoint);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resets all registered responses and captured requests, keeping only the default responses.
|
||||
/// </summary>
|
||||
public void Reset()
|
||||
{
|
||||
_getResponseFactories.Clear();
|
||||
_postResponseFactories.Clear();
|
||||
_putResponseFactories.Clear();
|
||||
_deleteSuccessEndpoints.Clear();
|
||||
GetEndpointsCalled.Clear();
|
||||
PostRequests.Clear();
|
||||
PutRequests.Clear();
|
||||
DeleteEndpointsCalled.Clear();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends a GET request to the specified <paramref name="endpoint"/> as an asynchronous operation and returns the result.
|
||||
/// </summary>
|
||||
/// <typeparam name="TResponse">The expected type of the response content.</typeparam>
|
||||
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The deserialized response containing the result of the GET request.</returns>
|
||||
public Task<TResponse> GetAsync<TResponse>(string endpoint, CancellationToken cancellationToken = default)
|
||||
{
|
||||
GetEndpointsCalled.Add(endpoint);
|
||||
if (_getResponseFactories.TryGetValue(endpoint, out Func<object>? responseFactory))
|
||||
return Task.FromResult((TResponse)responseFactory());
|
||||
if (endpoint.StartsWith(ApiRoutes.Initialization.CHECK_INITIALIZATION, StringComparison.OrdinalIgnoreCase))
|
||||
return Task.FromResult((TResponse)(object)InitializationResponse);
|
||||
if (endpoint.Contains("auth/get-authorization", StringComparison.OrdinalIgnoreCase))
|
||||
return Task.FromResult((TResponse)(object)AuthorizationResponse);
|
||||
throw new InvalidOperationException($"No GET response is registered for the endpoint '{endpoint}'.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends a GET request to the specified <paramref name="endpoint"/> as an asynchronous operation and returns the result as a streamable response.
|
||||
/// </summary>
|
||||
/// <typeparam name="TResponse">The expected type of the response content.</typeparam>
|
||||
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="IAsyncEnumerable{T}"/> object, which allows for asynchronous iteration over the deserialized items.</returns>
|
||||
public async IAsyncEnumerable<TResponse?> GetAsyncEnumerable<TResponse>(string endpoint, [EnumeratorCancellation] CancellationToken cancellationToken = default)
|
||||
{
|
||||
await Task.CompletedTask;
|
||||
yield break;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends a GET request to the specified <paramref name="endpoint"/> as an asynchronous operation and returns the result.
|
||||
/// </summary>
|
||||
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>A model containing the deserialized blob.</returns>
|
||||
public Task<BlobDataDto> GetBlobAsync(string endpoint, CancellationToken cancellationToken = default)
|
||||
{
|
||||
throw new NotSupportedException("Blob retrieval is not supported by the test stub.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends a DELETE request to the specified <paramref name="endpoint"/> as an asynchronous operation.
|
||||
/// </summary>
|
||||
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public Task DeleteAsync(string endpoint, CancellationToken cancellationToken = default)
|
||||
{
|
||||
DeleteEndpointsCalled.Add(endpoint);
|
||||
if (_deleteSuccessEndpoints.Contains(endpoint))
|
||||
return Task.CompletedTask;
|
||||
throw new ApiException(null, System.Net.HttpStatusCode.InternalServerError, endpoint);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends a PUT request to the specified <paramref name="endpoint"/> as an asynchronous operation and returns the result.
|
||||
/// </summary>
|
||||
/// <typeparam name="TResponse">The expected type of the response content.</typeparam>
|
||||
/// <typeparam name="TModel">The expected type of the payload content.</typeparam>
|
||||
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
||||
/// <param name="data">The data to be serialized and send to the API.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The deserialized response containing the result of the PUT request.</returns>
|
||||
public Task<TResponse> PutAsync<TResponse, TModel>(string endpoint, TModel data, CancellationToken cancellationToken = default)
|
||||
{
|
||||
PutRequests.Add((endpoint, data));
|
||||
if (_putResponseFactories.TryGetValue(endpoint, out Func<object, object>? responseFactory))
|
||||
return Task.FromResult((TResponse)responseFactory(data!));
|
||||
throw new InvalidOperationException($"No PUT response is registered for the endpoint '{endpoint}'.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends a POST request to the specified <paramref name="endpoint"/> as an asynchronous operation and returns the result.
|
||||
/// </summary>
|
||||
/// <typeparam name="TResponse">The expected type of the response content.</typeparam>
|
||||
/// <typeparam name="TModel">The expected type of the payload content.</typeparam>
|
||||
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
||||
/// <param name="data">The data to be serialized and send to the API.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The deserialized response containing the result of the POST request.</returns>
|
||||
public Task<TResponse> PostAsync<TResponse, TModel>(string endpoint, TModel data, CancellationToken cancellationToken = default)
|
||||
{
|
||||
PostRequests.Add((endpoint, data));
|
||||
if (_postResponseFactories.TryGetValue(endpoint, out Func<object, object>? responseFactory))
|
||||
return Task.FromResult((TResponse)responseFactory(data!));
|
||||
if (endpoint == ApiRoutes.Authentication.LOGIN_ACCOUNT)
|
||||
return Task.FromResult((TResponse)(object)LoginResponse);
|
||||
throw new InvalidOperationException($"No POST response is registered for the endpoint '{endpoint}'.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.Api;
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="HttpMessageHandler"/> test double that returns a configurable response for every request sent through it.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class TestApiHttpMessageHandler : HttpMessageHandler
|
||||
{
|
||||
private readonly Func<HttpRequestMessage, HttpResponseMessage> _responseFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the list of requests that were sent through this handler.
|
||||
/// </summary>
|
||||
public List<HttpRequestMessage> Requests { get; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets the bodies of the requests that were sent through this handler, captured while the request content is still available.
|
||||
/// </summary>
|
||||
public List<string?> RequestBodies { get; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="TestApiHttpMessageHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="responseFactory">The factory that produces the response for a given request.</param>
|
||||
public TestApiHttpMessageHandler(Func<HttpRequestMessage, HttpResponseMessage> responseFactory)
|
||||
{
|
||||
_responseFactory = responseFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends the request to the configured response factory.
|
||||
/// </summary>
|
||||
/// <param name="request">The HTTP request message to send.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The configured HTTP response message.</returns>
|
||||
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
Requests.Add(request);
|
||||
RequestBodies.Add(request.Content is null ? null : await request.Content.ReadAsStringAsync(cancellationToken));
|
||||
return await Task.FromResult(_responseFactory(request));
|
||||
}
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.DTO.Authorization;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Authorization;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for generating <see cref="RoleDto"/> test data.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RoleDtoFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="RoleDto"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="id">Optional identifier of the role.</param>
|
||||
/// <param name="roleName">Optional name of the role.</param>
|
||||
/// <returns>A configured <see cref="RoleDto"/> instance.</returns>
|
||||
public RoleDto Create(Guid? id = null, string? roleName = null)
|
||||
{
|
||||
Faker faker = new();
|
||||
return new RoleDto(
|
||||
Id: id ?? Guid.NewGuid(),
|
||||
RoleName: roleName ?? faker.Commerce.Department()
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="RoleDto"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="RoleDto"/> instances.</returns>
|
||||
public List<RoleDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.DTO.Libraries;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for generating <see cref="LibraryDto"/> test data.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LibraryDtoFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="LibraryDto"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="id">Optional identifier of the media library.</param>
|
||||
/// <param name="title">Optional title of the library.</param>
|
||||
/// <param name="libraryType">Optional type of the library.</param>
|
||||
/// <param name="isEnabled">Whether the media library is enabled or not.</param>
|
||||
/// <param name="contentLocations">Optional collection of directories that contain the library files.</param>
|
||||
/// <returns>A configured <see cref="LibraryDto"/> instance.</returns>
|
||||
public LibraryDto Create(Guid? id = null, string? title = null, string? libraryType = null, bool? isEnabled = null, List<string>? contentLocations = null)
|
||||
{
|
||||
Faker faker = new();
|
||||
return new LibraryDto
|
||||
{
|
||||
Id = id ?? Guid.NewGuid(),
|
||||
UserId = Guid.NewGuid(),
|
||||
Title = title ?? faker.Commerce.Department(),
|
||||
LibraryType = libraryType ?? faker.PickRandom("Book", "Video", "Photo"),
|
||||
CoverImage = faker.Image.PicsumUrl(),
|
||||
ContentLocations = contentLocations ?? [faker.System.DirectoryPath()],
|
||||
IsEnabled = isEnabled ?? faker.Random.Bool()
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="LibraryDto"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="LibraryDto"/> instances.</returns>
|
||||
public List<LibraryDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.DTO.UsersManagement;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.DTO.UsersManagement;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for generating <see cref="UserSettingsDto"/> test data.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UserSettingsDtoFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="UserSettingsDto"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="userId">Optional identifier of the user that owns the settings.</param>
|
||||
/// <param name="isPaginationEnabled">Whether pagination is enabled for the user.</param>
|
||||
/// <param name="itemsPerPage">Number of library items displayed per page.</param>
|
||||
/// <param name="ignoreThePrefixForAlphaPicker">Whether the "The" prefix is ignored by the alpha picker.</param>
|
||||
/// <returns>A configured <see cref="UserSettingsDto"/> instance.</returns>
|
||||
public UserSettingsDto Create(Guid? userId = null, bool? isPaginationEnabled = null, int? itemsPerPage = null, bool? ignoreThePrefixForAlphaPicker = null)
|
||||
{
|
||||
Faker faker = new();
|
||||
return new UserSettingsDto
|
||||
{
|
||||
UserId = userId ?? Guid.NewGuid(),
|
||||
IsPaginationEnabled = isPaginationEnabled ?? faker.Random.Bool(),
|
||||
ItemsPerPage = itemsPerPage ?? faker.Random.Int(1, 200),
|
||||
IgnoreThePrefixForAlphaPicker = ignoreThePrefixForAlphaPicker ?? faker.Random.Bool()
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="UserSettingsDto"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="UserSettingsDto"/> instances.</returns>
|
||||
public List<UserSettingsDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.Requests.Authorization;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Authorization;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for generating <see cref="AddRoleRequest"/> test data.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddRoleRequestFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="AddRoleRequest"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="roleName">Optional name of the role.</param>
|
||||
/// <param name="permissions">Optional collection of permission identifiers.</param>
|
||||
/// <returns>A configured <see cref="AddRoleRequest"/> instance.</returns>
|
||||
public AddRoleRequest Create(string? roleName = null, List<Guid>? permissions = null)
|
||||
{
|
||||
Faker faker = new();
|
||||
return new AddRoleRequest(
|
||||
RoleName: roleName ?? faker.Commerce.Department(),
|
||||
Permissions: permissions ?? [Guid.NewGuid(), Guid.NewGuid()]
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="AddRoleRequest"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="AddRoleRequest"/> instances.</returns>
|
||||
public List<AddRoleRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.Requests.Authorization;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Authorization;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for generating <see cref="DeleteRoleRequest"/> test data.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteRoleRequestFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="DeleteRoleRequest"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="roleId">Optional identifier of the role.</param>
|
||||
/// <returns>A configured <see cref="DeleteRoleRequest"/> instance.</returns>
|
||||
public DeleteRoleRequest Create(Guid? roleId = null)
|
||||
{
|
||||
return new DeleteRoleRequest(
|
||||
RoleId: roleId ?? Guid.NewGuid()
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="DeleteRoleRequest"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="DeleteRoleRequest"/> instances.</returns>
|
||||
public List<DeleteRoleRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Requests.FileSystemManagement.Directories;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.Requests.FileSystemManagement.Directories;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for generating <see cref="GetDirectoriesRequest"/> test data.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetDirectoriesRequestFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="GetDirectoriesRequest"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="path">Optional file system path whose directories are retrieved.</param>
|
||||
/// <param name="includeHiddenElements">Whether hidden file system elements are included or not.</param>
|
||||
/// <returns>A configured <see cref="GetDirectoriesRequest"/> instance.</returns>
|
||||
public GetDirectoriesRequest Create(string? path = null, bool includeHiddenElements = false)
|
||||
{
|
||||
return new GetDirectoriesRequest(
|
||||
Path: path ?? $"/media/{System.Guid.NewGuid():N}",
|
||||
IncludeHiddenElements: includeHiddenElements
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="GetDirectoriesRequest"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="GetDirectoriesRequest"/> instances.</returns>
|
||||
public List<GetDirectoriesRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Requests.FileSystemManagement.Path;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.Requests.FileSystemManagement.Path;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for generating <see cref="ValidatePathRequest"/> test data.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ValidatePathRequestFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="ValidatePathRequest"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="path">Optional file system path to validate.</param>
|
||||
/// <returns>A configured <see cref="ValidatePathRequest"/> instance.</returns>
|
||||
public ValidatePathRequest Create(string? path = null)
|
||||
{
|
||||
return new ValidatePathRequest(
|
||||
Path: path ?? $"/media/{System.Guid.NewGuid():N}"
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="ValidatePathRequest"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="ValidatePathRequest"/> instances.</returns>
|
||||
public List<ValidatePathRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.Enums.Common;
|
||||
using Lumina.Presentation.Web.Common.Requests.Libraries;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Libraries;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for generating <see cref="GetBooksLiteRequest"/> test data.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetBooksLiteRequestFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="GetBooksLiteRequest"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">Optional identifier of the media library.</param>
|
||||
/// <param name="currentPage">Optional page of results to retrieve.</param>
|
||||
/// <param name="perPage">Optional number of books to retrieve per page.</param>
|
||||
/// <param name="searchTerm">Optional search term used to filter results.</param>
|
||||
/// <param name="filterAlphaKey">Optional alpha key used to filter the results.</param>
|
||||
/// <param name="ignoreThePrefixForAlphaPicker">Whether the leading "The " prefix is ignored by the alpha picker.</param>
|
||||
/// <param name="sortBy">Optional name of the field by which to sort the results.</param>
|
||||
/// <param name="sortOrder">Optional direction in which to sort the results.</param>
|
||||
/// <returns>A configured <see cref="GetBooksLiteRequest"/> instance.</returns>
|
||||
public GetBooksLiteRequest Create(
|
||||
Guid? libraryId = null,
|
||||
int? currentPage = null,
|
||||
int? perPage = null,
|
||||
string? searchTerm = null,
|
||||
string? filterAlphaKey = null,
|
||||
bool ignoreThePrefixForAlphaPicker = false,
|
||||
string? sortBy = null,
|
||||
SortOrder? sortOrder = null)
|
||||
{
|
||||
return new GetBooksLiteRequest
|
||||
{
|
||||
LibraryId = libraryId ?? Guid.NewGuid(),
|
||||
CurrentPage = currentPage,
|
||||
PerPage = perPage,
|
||||
SearchTerm = searchTerm,
|
||||
FilterAlphaKey = filterAlphaKey,
|
||||
IgnoreThePrefixForAlphaPicker = ignoreThePrefixForAlphaPicker,
|
||||
SortBy = sortBy,
|
||||
SortOrder = sortOrder
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="GetBooksLiteRequest"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="GetBooksLiteRequest"/> instances.</returns>
|
||||
public List<GetBooksLiteRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.Management;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Management;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for generating <see cref="DeleteLibraryRequest"/> test data.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteLibraryRequestFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="DeleteLibraryRequest"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="id">Optional identifier of the media library.</param>
|
||||
/// <returns>A configured <see cref="DeleteLibraryRequest"/> instance.</returns>
|
||||
public DeleteLibraryRequest Create(Guid? id = null)
|
||||
{
|
||||
return new DeleteLibraryRequest(
|
||||
Id: id ?? Guid.NewGuid()
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="DeleteLibraryRequest"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="DeleteLibraryRequest"/> instances.</returns>
|
||||
public List<DeleteLibraryRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.Requests.Plugins;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for generating <see cref="UpdatePluginSettingsRequest"/> test data.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdatePluginSettingsRequestFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="UpdatePluginSettingsRequest"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="pluginId">Optional identifier of the plugin.</param>
|
||||
/// <param name="settings">Optional dictionary of settings.</param>
|
||||
/// <returns>A configured <see cref="UpdatePluginSettingsRequest"/> instance.</returns>
|
||||
public UpdatePluginSettingsRequest Create(Guid? pluginId = null, Dictionary<string, string>? settings = null)
|
||||
{
|
||||
Faker faker = new();
|
||||
return new UpdatePluginSettingsRequest
|
||||
{
|
||||
PluginId = pluginId ?? Guid.NewGuid(),
|
||||
Settings = settings ?? new Dictionary<string, string> { [faker.Lorem.Word()] = faker.Lorem.Word() }
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="UpdatePluginSettingsRequest"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="UpdatePluginSettingsRequest"/> instances.</returns>
|
||||
public List<UpdatePluginSettingsRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.Requests.Tools;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Tools;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for generating <see cref="SetLanguageRequest"/> test data.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SetLanguageRequestFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="SetLanguageRequest"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="newCulture">Optional new culture to set.</param>
|
||||
/// <param name="returnUrl">Optional URL to return to, after setting the new culture.</param>
|
||||
/// <returns>A configured <see cref="SetLanguageRequest"/> instance.</returns>
|
||||
public SetLanguageRequest Create(string? newCulture = "en-US", string? returnUrl = null)
|
||||
{
|
||||
return new SetLanguageRequest(
|
||||
NewCulture: newCulture,
|
||||
ReturnUrl: returnUrl
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="SetLanguageRequest"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="SetLanguageRequest"/> instances.</returns>
|
||||
public List<SetLanguageRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.Requests.UsersManagement.Authentication;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.Requests.UsersManagement.Authentication;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for generating <see cref="LoginViewRequest"/> test data.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LoginViewRequestFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="LoginViewRequest"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="returnUrl">Optional URL to return to, after login.</param>
|
||||
/// <returns>A configured <see cref="LoginViewRequest"/> instance.</returns>
|
||||
public LoginViewRequest Create(string? returnUrl = null)
|
||||
{
|
||||
Faker faker = new();
|
||||
return new LoginViewRequest(
|
||||
ReturnUrl: returnUrl ?? $"/{faker.Random.AlphaNumeric(8)}"
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="LoginViewRequest"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="LoginViewRequest"/> instances.</returns>
|
||||
public List<LoginViewRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.Requests.UsersManagement;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.Requests.UsersManagement;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for generating <see cref="ChangePasswordRequest"/> test data.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ChangePasswordRequestFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="ChangePasswordRequest"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="username">Optional username.</param>
|
||||
/// <param name="currentPassword">Optional current password.</param>
|
||||
/// <param name="newPassword">Optional new password.</param>
|
||||
/// <param name="newPasswordConfirm">Optional confirmation of the new password.</param>
|
||||
/// <returns>A configured <see cref="ChangePasswordRequest"/> instance.</returns>
|
||||
public ChangePasswordRequest Create(string? username = null, string? currentPassword = null, string? newPassword = null, string? newPasswordConfirm = null)
|
||||
{
|
||||
Faker faker = new();
|
||||
string generatedNewPassword = newPassword ?? faker.Internet.Password(12);
|
||||
return new ChangePasswordRequest(
|
||||
Username: username ?? faker.Internet.UserName(),
|
||||
CurrentPassword: currentPassword ?? faker.Internet.Password(12),
|
||||
NewPassword: generatedNewPassword,
|
||||
NewPasswordConfirm: newPasswordConfirm ?? generatedNewPassword
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="ChangePasswordRequest"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="ChangePasswordRequest"/> instances.</returns>
|
||||
public List<ChangePasswordRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.Requests.UsersManagement;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.Requests.UsersManagement;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for generating <see cref="LoginRequest"/> test data.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LoginRequestFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="LoginRequest"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="username">Optional username.</param>
|
||||
/// <param name="password">Optional password.</param>
|
||||
/// <param name="totpCode">Optional TOTP code.</param>
|
||||
/// <param name="returnUrl">Optional URL to return to, after login.</param>
|
||||
/// <returns>A configured <see cref="LoginRequest"/> instance.</returns>
|
||||
public LoginRequest Create(string? username = null, string? password = null, string? totpCode = null, string? returnUrl = null)
|
||||
{
|
||||
Faker faker = new();
|
||||
return new LoginRequest(
|
||||
Username: username ?? faker.Internet.UserName(),
|
||||
Password: password ?? faker.Internet.Password(12),
|
||||
TotpCode: totpCode,
|
||||
ReturnUrl: returnUrl
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="LoginRequest"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="LoginRequest"/> instances.</returns>
|
||||
public List<LoginRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.Requests.UsersManagement;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.Requests.UsersManagement;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for generating <see cref="RecoverPasswordRequest"/> test data.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RecoverPasswordRequestFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="RecoverPasswordRequest"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="username">Optional username.</param>
|
||||
/// <param name="totpCode">Optional TOTP code.</param>
|
||||
/// <returns>A configured <see cref="RecoverPasswordRequest"/> instance.</returns>
|
||||
public RecoverPasswordRequest Create(string? username = null, string? totpCode = null)
|
||||
{
|
||||
Faker faker = new();
|
||||
return new RecoverPasswordRequest(
|
||||
Username: username ?? faker.Internet.UserName(),
|
||||
TotpCode: totpCode
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="RecoverPasswordRequest"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="RecoverPasswordRequest"/> instances.</returns>
|
||||
public List<RecoverPasswordRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.Requests.UsersManagement;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.Requests.UsersManagement;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for generating <see cref="RegisterRequest"/> test data.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RegisterRequestFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="RegisterRequest"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="username">Optional username.</param>
|
||||
/// <param name="password">Optional password.</param>
|
||||
/// <param name="passwordConfirm">Optional password confirmation.</param>
|
||||
/// <param name="registrationType">Optional registration type, e.g. "Admin" or "User".</param>
|
||||
/// <param name="use2fa">Whether two-factor authentication is enabled for the account.</param>
|
||||
/// <returns>A configured <see cref="RegisterRequest"/> instance.</returns>
|
||||
public RegisterRequest Create(string? username = null, string? password = null, string? passwordConfirm = null, string? registrationType = "User", bool use2fa = true)
|
||||
{
|
||||
Faker faker = new();
|
||||
string generatedPassword = password ?? faker.Internet.Password(12);
|
||||
return new RegisterRequest(
|
||||
Username: username ?? faker.Internet.UserName(),
|
||||
Password: generatedPassword,
|
||||
PasswordConfirm: passwordConfirm ?? generatedPassword,
|
||||
RegistrationType: registrationType,
|
||||
Use2fa: use2fa
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="RegisterRequest"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="RegisterRequest"/> instances.</returns>
|
||||
public List<RegisterRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
|
||||
/// <summary>
|
||||
/// Helper for executing <see cref="IResult"/> instances and reading the JSON response body they produce.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public static class JsonResultTestHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// Executes the specified <paramref name="result"/> against a fresh HTTP context and reads the response body.
|
||||
/// </summary>
|
||||
/// <param name="result">The result to execute.</param>
|
||||
/// <param name="httpContext">Optional HTTP context to execute the result against; a fresh context is created when not provided.</param>
|
||||
/// <returns>The response body produced by the result.</returns>
|
||||
public static async Task<string> GetResponseBodyAsync(IResult result, HttpContext? httpContext = null)
|
||||
{
|
||||
DefaultHttpContext context = httpContext as DefaultHttpContext ?? TestHttpContextFactory.Create();
|
||||
await result.ExecuteAsync(context);
|
||||
context.Response.Body.Position = 0;
|
||||
return await new StreamReader(context.Response.Body).ReadToEndAsync();
|
||||
}
|
||||
}
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.Features;
|
||||
using Microsoft.AspNetCore.Http.Json;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Security.Claims;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
|
||||
/// <summary>
|
||||
/// Factory for creating and configuring <see cref="HttpContext"/> instances for unit testing Web endpoints.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public static class TestHttpContextFactory
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a <see cref="DefaultHttpContext"/> with a writable response body, optional culture route value, session and user.
|
||||
/// </summary>
|
||||
/// <param name="culture">The value of the <c>culture</c> route value.</param>
|
||||
/// <param name="user">The user associated with the context, <see langword="null"/> for anonymous requests.</param>
|
||||
/// <param name="session">The session associated with the context, <see langword="null"/> when no session is available.</param>
|
||||
/// <returns>A configured <see cref="DefaultHttpContext"/> instance.</returns>
|
||||
public static DefaultHttpContext Create(string? culture = "en-US", ClaimsPrincipal? user = null, ISession? session = null)
|
||||
{
|
||||
DefaultHttpContext httpContext = new();
|
||||
// provide a writable response body, so that executed IResult instances can be inspected by the tests
|
||||
httpContext.Features.Set<IHttpResponseBodyFeature>(new StreamResponseBodyFeature(new MemoryStream()));
|
||||
// provide the minimal services needed by the result execution machinery (logging, options, JSON options)
|
||||
httpContext.RequestServices = CreateServiceProvider();
|
||||
httpContext.Request.RouteValues["culture"] = culture;
|
||||
if (user is not null)
|
||||
httpContext.User = user;
|
||||
if (session is not null)
|
||||
httpContext.Features.Set<ISessionFeature>(new TestSessionFeature { Session = session });
|
||||
return httpContext;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a service provider that provides the minimal services needed by the result execution machinery.
|
||||
/// </summary>
|
||||
/// <returns>A configured <see cref="IServiceProvider"/> instance.</returns>
|
||||
public static IServiceProvider CreateServiceProvider()
|
||||
{
|
||||
ServiceCollection services = new();
|
||||
services.AddLogging();
|
||||
services.AddOptions();
|
||||
services.Configure<JsonOptions>(jsonOptions => jsonOptions.SerializerOptions.MaxDepth = 256);
|
||||
return services.BuildServiceProvider();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Attaches a session to the provided HTTP context.
|
||||
/// </summary>
|
||||
/// <param name="httpContext">The HTTP context to configure.</param>
|
||||
/// <param name="session">The session to attach.</param>
|
||||
public static void ConfigureSession(HttpContext httpContext, ISession session)
|
||||
{
|
||||
httpContext.Features.Set<ISessionFeature>(new TestSessionFeature { Session = session });
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Attaches a user to the provided HTTP context.
|
||||
/// </summary>
|
||||
/// <param name="httpContext">The HTTP context to configure.</param>
|
||||
/// <param name="user">The user to attach.</param>
|
||||
public static void ConfigureUser(HttpContext httpContext, ClaimsPrincipal user)
|
||||
{
|
||||
httpContext.User = user;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the value of the <c>culture</c> route value of the provided HTTP context.
|
||||
/// </summary>
|
||||
/// <param name="httpContext">The HTTP context to configure.</param>
|
||||
/// <param name="culture">The culture to set.</param>
|
||||
public static void ConfigureCulture(HttpContext httpContext, string? culture)
|
||||
{
|
||||
httpContext.Request.RouteValues["culture"] = culture;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a mock <see cref="ISession"/> that supports the <c>GetString</c> and <c>SetString</c> extension methods.
|
||||
/// </summary>
|
||||
/// <returns>A mock <see cref="ISession"/> instance.</returns>
|
||||
public static ISession CreateSession()
|
||||
{
|
||||
ISession session = Substitute.For<ISession>();
|
||||
#pragma warning disable CS8601 // possible null reference assignment in the NSubstitute out-argument stub
|
||||
session.TryGetValue(Arg.Any<string>(), out Arg.Any<byte[]>()).Returns(callInfo =>
|
||||
{
|
||||
callInfo[1] = null;
|
||||
return false;
|
||||
});
|
||||
#pragma warning restore CS8601
|
||||
return session;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an authenticated <see cref="ClaimsPrincipal"/> with the specified username.
|
||||
/// </summary>
|
||||
/// <param name="username">The username of the authenticated user.</param>
|
||||
/// <returns>An authenticated <see cref="ClaimsPrincipal"/> instance.</returns>
|
||||
public static ClaimsPrincipal CreateAuthenticatedUser(string username = "testuser")
|
||||
{
|
||||
return new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.Name, username)], "TestAuthentication"));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Minimal <see cref="ISessionFeature"/> implementation used to attach a session to test HTTP contexts.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
private sealed class TestSessionFeature : ISessionFeature
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the session associated with the feature.
|
||||
/// </summary>
|
||||
public ISession Session { get; set; } = null!;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web;
|
||||
using Lumina.Presentation.Web.Common.Requests.UsersManagement;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
|
||||
/// <summary>
|
||||
/// Represents an HTTP client that has been authenticated through the real login flow of the Web application.
|
||||
/// </summary>
|
||||
/// <param name="Client">The authenticated HTTP client.</param>
|
||||
/// <param name="AntiforgeryToken">The antiforgery token captured before the login, valid for subsequent mutating requests.</param>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public record AuthenticatedWebClient(HttpClient Client, string AntiforgeryToken);
|
||||
|
||||
/// <summary>
|
||||
/// Helper methods for exercising the authentication and antiforgery flows of the Web application in integration and security tests.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public static partial class WebTestHelpers
|
||||
{
|
||||
private const string LOGIN_PAGE_PATH = "/en-us/auth/login";
|
||||
private const string LOGIN_ENDPOINT_PATH = "/en-us/auth/api-login";
|
||||
|
||||
[GeneratedRegex("name=\"__RequestVerificationToken\"[^>]*value=\"([^\"]*)\"")]
|
||||
private static partial Regex AntiforgeryTokenRegex();
|
||||
|
||||
/// <summary>
|
||||
/// Creates an anonymous HTTP client that does not follow redirects.
|
||||
/// </summary>
|
||||
/// <param name="factory">The Web application factory.</param>
|
||||
/// <returns>An anonymous HTTP client.</returns>
|
||||
public static HttpClient CreateAnonymousClient(WebApplicationFactory<Program> factory)
|
||||
{
|
||||
return factory.CreateClient(new WebApplicationFactoryClientOptions { AllowAutoRedirect = false });
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an HTTP client that has been authenticated through the real login flow of the application.
|
||||
/// </summary>
|
||||
/// <param name="factory">The Web application factory.</param>
|
||||
/// <param name="username">The username to authenticate with.</param>
|
||||
/// <param name="password">The password to authenticate with.</param>
|
||||
/// <returns>An HTTP client authenticated with the application's authentication cookie, together with an antiforgery token.</returns>
|
||||
public static async Task<AuthenticatedWebClient> CreateAuthenticatedClientAsync(WebApplicationFactory<Program> factory, string? username = "testuser", string? password = "TestPass123!")
|
||||
{
|
||||
// the application marks its cookies as secure, so the test client must communicate over HTTPS for the cookies to be sent back
|
||||
HttpClient client = factory.CreateClient(new WebApplicationFactoryClientOptions
|
||||
{
|
||||
BaseAddress = new Uri("https://localhost"),
|
||||
AllowAutoRedirect = false
|
||||
});
|
||||
string antiforgeryToken = await GetAntiforgeryTokenAsync(client);
|
||||
await LoginAsync(client, username!, password!, antiforgeryToken);
|
||||
return new AuthenticatedWebClient(client, antiforgeryToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Performs the login flow of the application against the provided client.
|
||||
/// </summary>
|
||||
/// <param name="client">The HTTP client to log in through.</param>
|
||||
/// <param name="username">The username to authenticate with.</param>
|
||||
/// <param name="password">The password to authenticate with.</param>
|
||||
/// <param name="antiforgeryToken">The antiforgery token to send with the login request.</param>
|
||||
public static async Task LoginAsync(HttpClient client, string username, string password, string antiforgeryToken)
|
||||
{
|
||||
HttpRequestMessage loginRequest = new(HttpMethod.Post, LOGIN_ENDPOINT_PATH)
|
||||
{
|
||||
Content = JsonContent.Create(new LoginRequest(Username: username, Password: password))
|
||||
};
|
||||
// the antiforgery middleware matches the content type exactly, so the charset suffix must be omitted
|
||||
loginRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
loginRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
loginRequest.Headers.Add("RequestVerificationToken", antiforgeryToken);
|
||||
HttpResponseMessage response = await client.SendAsync(loginRequest);
|
||||
response.EnsureSuccessStatusCode();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves the antiforgery token and cookie by requesting the login page.
|
||||
/// </summary>
|
||||
/// <param name="client">The HTTP client to retrieve the token through.</param>
|
||||
/// <returns>The antiforgery token value.</returns>
|
||||
public static async Task<string> GetAntiforgeryTokenAsync(HttpClient client)
|
||||
{
|
||||
HttpResponseMessage loginPageResponse = await client.GetAsync(LOGIN_PAGE_PATH);
|
||||
loginPageResponse.EnsureSuccessStatusCode();
|
||||
string loginPageHtml = await loginPageResponse.Content.ReadAsStringAsync();
|
||||
Match match = AntiforgeryTokenRegex().Match(loginPageHtml);
|
||||
if (!match.Success)
|
||||
throw new InvalidOperationException("Could not find the antiforgery token on the login page.");
|
||||
return System.Net.WebUtility.HtmlDecode(match.Groups[1].Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserializes a JSON response body into a <see cref="JsonDocument"/>.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response whose body is deserialized.</param>
|
||||
/// <returns>The parsed <see cref="JsonDocument"/>.</returns>
|
||||
public static async Task<JsonDocument> ReadJsonAsync(HttpResponseMessage response)
|
||||
{
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
return JsonDocument.Parse(content);
|
||||
}
|
||||
}
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Common;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Core.Endpoints.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="BaseEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
[DontRegister]
|
||||
public class BaseEndpointFixture : BaseEndpoint<EmptyRequest, IResult>
|
||||
{
|
||||
/// <summary>
|
||||
/// Exposes the <c>Culture</c> property of the <see cref="BaseEndpoint"/> class.
|
||||
/// </summary>
|
||||
public string TestCulture => Culture;
|
||||
|
||||
/// <summary>
|
||||
/// Renders a Razor view through the <see cref="BaseEndpoint.View(string, object?, IReadOnlyDictionary{string, object?})"/> helper.
|
||||
/// </summary>
|
||||
/// <param name="viewName">The name or path of the view to render.</param>
|
||||
/// <param name="model">The model to pass to the view.</param>
|
||||
/// <param name="viewData">Optional additional view data entries made available to the view via <c>ViewData</c>.</param>
|
||||
/// <returns>An <see cref="IResult"/> that renders the view.</returns>
|
||||
public IResult TestView(string viewName, object? model = null, IReadOnlyDictionary<string, object?>? viewData = null)
|
||||
{
|
||||
return View(viewName, model, viewData);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a JSON response indicating a successful operation through the <see cref="BaseEndpoint.JsonSuccess(object?)"/> helper.
|
||||
/// </summary>
|
||||
/// <param name="data">The payload of the successful response.</param>
|
||||
/// <returns>An <see cref="IResult"/> containing the success JSON payload.</returns>
|
||||
public IResult TestJsonSuccess(object? data)
|
||||
{
|
||||
return JsonSuccess(data);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a JSON response indicating a successful operation without a payload through the <see cref="BaseEndpoint.JsonSuccess()"/> helper.
|
||||
/// </summary>
|
||||
/// <returns>An <see cref="IResult"/> containing the success JSON payload.</returns>
|
||||
public IResult TestJsonSuccess()
|
||||
{
|
||||
return JsonSuccess();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures the endpoint.
|
||||
/// </summary>
|
||||
public override void Configure()
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the request.
|
||||
/// </summary>
|
||||
/// <param name="request">The request object.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="IResult"/> containing the success JSON payload.</returns>
|
||||
public override Task<IResult> ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
return Task.FromResult(TestJsonSuccess());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>disable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<BaseOutputPath>$(SolutionDir)..\bin\web\</BaseOutputPath>
|
||||
|
||||
<IsPackable>false</IsPackable>
|
||||
<IsTestProject>false</IsTestProject>
|
||||
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AutoFixture" Version="5.0.0-preview0011" />
|
||||
<PackageReference Include="AutoFixture.AutoNSubstitute" Version="5.0.0-preview0011" />
|
||||
<PackageReference Include="AutoFixture.Xunit2" Version="5.0.0-preview0011" />
|
||||
<PackageReference Include="Bogus" Version="35.6.5" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.11" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\src\Lumina.Presentation.Web\Lumina.Presentation.Web.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,22 @@
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
// General Information about an assembly is controlled through the following
|
||||
// set of attributes. Change these attribute values to modify the information
|
||||
// associated with an assembly.
|
||||
[assembly: AssemblyTitle("Lumina.Presentation.Web.Fixtures")]
|
||||
[assembly: AssemblyProduct("Lumina.Presentation.Web.Fixtures")]
|
||||
|
||||
// Setting ComVisible to false makes the types in this assembly not visible
|
||||
// to COM components. If you need to access a type in this assembly from
|
||||
// COM, set the ComVisible attribute to true on that type.
|
||||
[assembly: ComVisible(false)]
|
||||
|
||||
// The following GUID is for the ID of the typelib if this project is exposed to COM
|
||||
[assembly: Guid("B7C8D9E0-0001-4C5D-8E1F-222222222222")]
|
||||
|
||||
[assembly: InternalsVisibleTo("Lumina.Presentation.Web.UnitTests")]
|
||||
[assembly: InternalsVisibleTo("Lumina.Presentation.Web.IntegrationTests")]
|
||||
[assembly: InternalsVisibleTo("Lumina.Presentation.Web.SecurityTests")]
|
||||
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
|
||||
+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);
|
||||
}
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
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 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>
|
||||
/// 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)).ToArray();
|
||||
foreach (ServiceDescriptor descriptor in apiClientDescriptors)
|
||||
services.Remove(descriptor);
|
||||
services.AddSingleton<IApiHttpClient>(ApiClientStub);
|
||||
});
|
||||
}
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Authorization;
|
||||
using Lumina.Presentation.Web.Common.Responses.Authorization;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Admin.Authorization.Roles.GetRoles;
|
||||
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 <c>/{culture}/admin/api-get-roles</c> route served by the <see cref="GetRolesEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetRolesEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <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 = new GetAuthorizationResponse(Guid.NewGuid(), "Admin", []);
|
||||
RoleDto[] expectedRoles = [new RoleDto(Guid.NewGuid(), "Admin"), new RoleDto(Guid.NewGuid(), "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 = new GetAuthorizationResponse(Guid.NewGuid(), "User", []);
|
||||
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());
|
||||
}
|
||||
}
|
||||
+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 <c>/{culture}</c> and <c>/</c> routes served by 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);
|
||||
}
|
||||
}
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraries;
|
||||
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 <c>/{culture}/libraries/manage/api-get-libraries</c> route served by the <see cref="GetLibrariesEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetLibrariesEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <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 =
|
||||
[
|
||||
new LibraryDto { Id = Guid.NewGuid(), Title = "Books", LibraryType = "Book" },
|
||||
new LibraryDto { 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);
|
||||
}
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.SaveLibrary;
|
||||
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 <c>/{culture}/libraries/manage/api-item</c> route served by the <see cref="SaveLibraryEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SaveLibraryEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <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 = new() { Title = "New Books Library", LibraryType = "Book" };
|
||||
LibraryDto expectedResponse = new() { 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_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(new LibraryDto { 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");
|
||||
}
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Tools.Language.SetLanguage;
|
||||
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.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Tools.Language.SetLanguage;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <c>/{culture}/tools/language/set-language</c> route served by the <see cref="SetLanguageEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SetLanguageEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SetLanguageEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public SetLanguageEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetLanguage_WhenCalledByAuthenticatedUser_ShouldSetCultureCookieAndRedirectWithNewCulture()
|
||||
{
|
||||
// Arrange
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
string returnUrl = Uri.EscapeDataString("/en-us/tools/settings");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/tools/language/set-language?newCulture=de-DE&returnUrl={returnUrl}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Equal("/de-de/tools/settings", response.Headers.Location!.ToString());
|
||||
Assert.Contains("de-DE", response.Headers.GetValues("Set-Cookie").First());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetLanguage_WhenCalledWithoutAuthentication_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.GetAsync("/en-us/tools/language/set-language?newCulture=de-DE");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
|
||||
}
|
||||
}
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Lumina.Presentation.Web.Common.Requests.UsersManagement;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.Login;
|
||||
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.IO;
|
||||
using System.Linq;
|
||||
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.UsersManagement.Authentication.Login;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <c>/{culture}/auth/api-login</c> route served by the <see cref="LoginEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LoginEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LoginEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public LoginEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Login_WithValidCredentials_ShouldSignInAndReturnRedirectUrl()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client);
|
||||
HttpRequestMessage loginRequest = CreateLoginRequest(new LoginRequest(Username: "testuser", Password: "TestPass123!"), antiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.SendAsync(loginRequest);
|
||||
using JsonDocument json = await WebTestHelpers.ReadJsonAsync(response);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal("/en-us/", json.RootElement.GetProperty("data").GetString());
|
||||
string allSetCookies = string.Join("; ", response.Headers.GetValues("Set-Cookie"));
|
||||
Assert.Contains(".Lumina.Auth", allSetCookies);
|
||||
Assert.Contains("Token=", allSetCookies);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Login_WhenTotpRequired_ShouldReturnTotpRequiredSignal()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
ProblemDetailsDto problemDetails = new()
|
||||
{
|
||||
Title = "General.Validation",
|
||||
Detail = "OneOrMoreValidationErrorsOccurred",
|
||||
Extensions = new Dictionary<string, JsonElement>
|
||||
{
|
||||
["errors"] = CreateErrorsElement(["InvalidTotpCode"])
|
||||
}
|
||||
};
|
||||
_apiFactory.ApiClientStub.RegisterPostException("auth/login", new ApiException(problemDetails, HttpStatusCode.UnprocessableEntity, "auth/login"));
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client);
|
||||
HttpRequestMessage loginRequest = CreateLoginRequest(new LoginRequest(Username: "testuser", Password: "TestPass123!"), antiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.SendAsync(loginRequest);
|
||||
using JsonDocument json = await WebTestHelpers.ReadJsonAsync(response);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.True(json.RootElement.GetProperty("data").GetProperty("isTotpRequired").GetBoolean());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Login_WhenApiReturnsForbidden_ShouldReturnFailureJson()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.RegisterPostException("auth/login", new ApiException(new ProblemDetailsDto { Title = "General.Failure", Detail = "InvalidUsernameOrPassword" }, HttpStatusCode.Forbidden, "auth/login"));
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client);
|
||||
HttpRequestMessage loginRequest = CreateLoginRequest(new LoginRequest(Username: "testuser", Password: "WrongPass123!"), antiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.SendAsync(loginRequest);
|
||||
using JsonDocument json = await WebTestHelpers.ReadJsonAsync(response);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Contains("<b>", json.RootElement.GetProperty("errorMessage").GetString());
|
||||
}
|
||||
|
||||
private static HttpRequestMessage CreateLoginRequest(LoginRequest request, string antiforgeryToken)
|
||||
{
|
||||
HttpRequestMessage loginRequest = new(HttpMethod.Post, "/en-us/auth/api-login")
|
||||
{
|
||||
Content = JsonContent.Create(request)
|
||||
};
|
||||
loginRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
loginRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
loginRequest.Headers.Add("RequestVerificationToken", antiforgeryToken);
|
||||
return loginRequest;
|
||||
}
|
||||
|
||||
private static JsonElement CreateErrorsElement(string[] errorCodes)
|
||||
{
|
||||
using MemoryStream stream = new();
|
||||
using (Utf8JsonWriter writer = new(stream))
|
||||
{
|
||||
writer.WriteStartObject();
|
||||
writer.WriteStartArray("General.Validation");
|
||||
foreach (string errorCode in errorCodes)
|
||||
writer.WriteStringValue(errorCode);
|
||||
writer.WriteEndArray();
|
||||
writer.WriteEndObject();
|
||||
}
|
||||
return JsonDocument.Parse(stream.ToArray()).RootElement.Clone();
|
||||
}
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.Login;
|
||||
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.UsersManagement.Authentication.Login;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <c>/{culture}/auth/login/{returnUrl?}</c> route served by the <see cref="LoginViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LoginViewEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LoginViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public LoginViewEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task LoginView_WhenCalled_ShouldRenderLoginPage()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.GetAsync("/en-us/auth/login");
|
||||
|
||||
// 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("login-form", content);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("/de-de/auth/login")] // German culture
|
||||
[InlineData("/fr-fr/auth/login")] // French culture
|
||||
[InlineData("/zh-cn/auth/login")] // Chinese culture
|
||||
public async Task LoginView_WhenCalledWithLocalizedCulture_ShouldRenderLoginPage(string culturePath)
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.GetAsync(culturePath);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.Contains("login-form", content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task LoginView_WhenCalledWithReturnUrl_ShouldPreserveReturnUrlInView()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.GetAsync("/en-us/auth/login/some-return-url");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.Contains("some-return-url", content);
|
||||
}
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>disable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
|
||||
<IsPackable>false</IsPackable>
|
||||
<IsTestProject>true</IsTestProject>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<AssemblyAttribute Include="Xunit.CollectionBehaviorAttribute">
|
||||
<_Parameter1>DisableTestParallelization = true</_Parameter1>
|
||||
<_Parameter1_IsLiteral>true</_Parameter1_IsLiteral>
|
||||
</AssemblyAttribute>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AutoFixture.AutoNSubstitute" Version="5.0.0-preview0011" />
|
||||
<PackageReference Include="AutoFixture.Xunit2" Version="5.0.0-preview0011" />
|
||||
<PackageReference Include="Bogus" Version="35.6.5" />
|
||||
<PackageReference Include="coverlet.collector" Version="10.0.1">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.11" />
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="10.0.11" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.9.0" />
|
||||
<PackageReference Include="NSubstitute" Version="6.2.0" />
|
||||
<PackageReference Include="xunit" Version="2.9.3" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="4.0.0">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Using Include="Xunit" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\src\Lumina.Presentation.Web\Lumina.Presentation.Web.csproj" />
|
||||
<ProjectReference Include="..\..\Common\Lumina.Presentation.Web.Fixtures\Lumina.Presentation.Web.Fixtures.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
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 System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Common.Setup;
|
||||
|
||||
/// <summary>
|
||||
/// Factory for creating the Web application for security 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>
|
||||
/// Initializes a new instance of the <see cref="LuminaWebFactory"/> class.
|
||||
/// </summary>
|
||||
public LuminaWebFactory()
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures the web host for the security 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)).ToArray();
|
||||
foreach (ServiceDescriptor descriptor in apiClientDescriptors)
|
||||
services.Remove(descriptor);
|
||||
services.AddSingleton<IApiHttpClient>(ApiClientStub);
|
||||
});
|
||||
}
|
||||
}
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Authorization;
|
||||
using Lumina.Presentation.Web.Common.Responses.Authorization;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Admin.Authorization.Roles.GetRoles;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.SecurityTests.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.SecurityTests.Core.Endpoints.Admin.Authorization.Roles.GetRoles;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <c>/{culture}/admin/api-get-roles</c> route served by the <see cref="GetRolesEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetRolesEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <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_WhenCalledWithoutAuthentication_ShouldNotExposeRoleData()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
RoleDto[] unexpectedRoles = [new RoleDto(Guid.NewGuid(), "Admin")];
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse("auth/roles", unexpectedRoles);
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.GetAsync("/en-us/admin/api-get-roles");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.DoesNotContain("Admin", content);
|
||||
Assert.DoesNotContain("AdminRole", content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRoles_WhenCalledByNonAdminUser_ShouldRedirectToAccessDenied()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.AuthorizationResponse = new GetAuthorizationResponse(Guid.NewGuid(), "User", []);
|
||||
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());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRoles_WhenCalledByAdminUser_ShouldReturnRolesData()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.AuthorizationResponse = new GetAuthorizationResponse(Guid.NewGuid(), "Admin", []);
|
||||
RoleDto[] expectedRoles = [new RoleDto(Guid.NewGuid(), "Admin")];
|
||||
_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");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
}
|
||||
}
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.DeleteLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.SecurityTests.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.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.DeleteLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <c>/{culture}/libraries/manage/api-item/{{id}}</c> route served by 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_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(libraryId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.DeleteEndpointsCalled, endpoint => endpoint == $"libraries/{libraryId}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteLibrary_WhenCalledWithoutAuthentication_ShouldNotDeleteLibrary()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client);
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(libraryId);
|
||||
deleteRequest.Headers.Add("RequestVerificationToken", antiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.SendAsync(deleteRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.DeleteEndpointsCalled, endpoint => endpoint == $"libraries/{libraryId}");
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.SaveLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.SecurityTests.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.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.SaveLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <c>/{culture}/libraries/manage/api-item</c> route served by the <see cref="SaveLibraryEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SaveLibraryEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <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_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage saveRequest = CreateSaveRequest(new LibraryDto { Title = "New Books Library", LibraryType = "Book" });
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "libraries");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveLibrary_WhenCalledWithInvalidAntiforgeryToken_ShouldRejectRequest()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage saveRequest = CreateSaveRequest(new LibraryDto { Title = "New Books Library", LibraryType = "Book" });
|
||||
saveRequest.Headers.Remove("RequestVerificationToken");
|
||||
saveRequest.Headers.Add("RequestVerificationToken", "invalid-antiforgery-token");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "libraries");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveLibrary_WhenCalledWithInjectionInLibraryTitle_ShouldRemainSecure()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
LibraryDto request = new() { Title = "'; DROP TABLE Libraries--", LibraryType = "Book" };
|
||||
_apiFactory.ApiClientStub.RegisterPostResponse("libraries", new LibraryDto { Id = Guid.NewGuid(), Title = request.Title, LibraryType = request.LibraryType });
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage saveRequest = CreateSaveRequest(request);
|
||||
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);
|
||||
Assert.DoesNotContain("SQL", content);
|
||||
Assert.DoesNotContain("Exception", content);
|
||||
}
|
||||
|
||||
private static HttpRequestMessage CreateSaveRequest(LibraryDto request)
|
||||
{
|
||||
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"));
|
||||
return saveRequest;
|
||||
}
|
||||
}
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Lumina.Presentation.Web.Common.Requests.UsersManagement;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.Login;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.SecurityTests.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.SecurityTests.Core.Endpoints.UsersManagement.Authentication.Login;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <c>/{culture}/auth/api-login</c> route served by the <see cref="LoginEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LoginEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LoginEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public LoginEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // basic SQL injection
|
||||
[InlineData("admin'--")] // comment injection
|
||||
[InlineData("' UNION SELECT * FROM Users--")] // union injection
|
||||
[InlineData("'; DROP TABLE Users--")] // destructive injection
|
||||
[InlineData("{{7*7}}")] // template injection
|
||||
public async Task Login_WithInjectionAttemptInUsername_ShouldRemainSecure(string maliciousUsername)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.RegisterPostException("auth/login", new ApiException(new ProblemDetailsDto { Title = "General.Failure", Detail = "InvalidUsernameOrPassword" }, HttpStatusCode.Forbidden, "auth/login"));
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client);
|
||||
HttpRequestMessage loginRequest = CreateLoginRequest(new LoginRequest(Username: maliciousUsername, Password: "Abcd123$"), antiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.SendAsync(loginRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.DoesNotContain("SQL", content);
|
||||
Assert.DoesNotContain("Exception", content);
|
||||
Assert.DoesNotContain("Abcd123$", content);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Login_WithValidCredentials_ShouldNotExposeSensitiveData()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client);
|
||||
HttpRequestMessage loginRequest = CreateLoginRequest(new LoginRequest(Username: "testuser", Password: "TestPass123!"), antiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.SendAsync(loginRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.DoesNotContain("TestPass123!", content);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
// the JWT token returned by the API must not be exposed in plaintext; it is stored encrypted in the Token cookie
|
||||
Assert.DoesNotContain("test_jwt_token", content);
|
||||
string allSetCookies = string.Join("; ", response.Headers.GetValues("Set-Cookie"));
|
||||
Assert.Contains("Token=", allSetCookies);
|
||||
Assert.DoesNotContain("test_jwt_token", allSetCookies);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Login_WhenCalled_ShouldSetAuthenticationCookieWithSecurityAttributes()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client);
|
||||
HttpRequestMessage loginRequest = CreateLoginRequest(new LoginRequest(Username: "testuser", Password: "TestPass123!"), antiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.SendAsync(loginRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
string authCookie = response.Headers.GetValues("Set-Cookie").First(cookie => cookie.StartsWith(".Lumina.Auth", StringComparison.Ordinal));
|
||||
Assert.Contains("httponly", authCookie, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Contains("secure", authCookie, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Contains("samesite=strict", authCookie, StringComparison.OrdinalIgnoreCase);
|
||||
string tokenCookie = response.Headers.GetValues("Set-Cookie").First(cookie => cookie.StartsWith("Token=", StringComparison.Ordinal) && !cookie.Contains("1970"));
|
||||
Assert.Contains("httponly", tokenCookie, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Contains("secure", tokenCookie, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Contains("samesite=strict", tokenCookie, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
private static HttpRequestMessage CreateLoginRequest(LoginRequest request, string antiforgeryToken)
|
||||
{
|
||||
HttpRequestMessage loginRequest = new(HttpMethod.Post, "/en-us/auth/api-login")
|
||||
{
|
||||
Content = JsonContent.Create(request)
|
||||
};
|
||||
loginRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
loginRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
loginRequest.Headers.Add("RequestVerificationToken", antiforgeryToken);
|
||||
return loginRequest;
|
||||
}
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
|
||||
<IsPackable>false</IsPackable>
|
||||
<IsTestProject>true</IsTestProject>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<AssemblyAttribute Include="Xunit.CollectionBehaviorAttribute">
|
||||
<_Parameter1>DisableTestParallelization = true</_Parameter1>
|
||||
<_Parameter1_IsLiteral>true</_Parameter1_IsLiteral>
|
||||
</AssemblyAttribute>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AutoFixture.AutoNSubstitute" Version="5.0.0-preview0011" />
|
||||
<PackageReference Include="AutoFixture.Xunit2" Version="5.0.0-preview0011" />
|
||||
<PackageReference Include="Bogus" Version="35.6.5" />
|
||||
<PackageReference Include="coverlet.collector" Version="10.0.1">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.11" />
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="10.0.11" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.9.0" />
|
||||
<PackageReference Include="NSubstitute" Version="6.2.0" />
|
||||
<PackageReference Include="xunit" Version="2.9.3" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="4.0.0">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Using Include="Xunit" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\src\Lumina.Presentation.Web\Lumina.Presentation.Web.csproj" />
|
||||
<ProjectReference Include="..\..\Common\Lumina.Presentation.Web.Fixtures\Lumina.Presentation.Web.Fixtures.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,177 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Common.DTO.Configuration;
|
||||
using Lumina.Presentation.Web.Common.DTO.FileSystemManagement;
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Api;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Options;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Common.Api;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ApiHttpClient"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ApiHttpClientTests
|
||||
{
|
||||
private const string TEST_ENCRYPTION_KEY = "FLYO0QRo6u2VzoFOgNkkEwYNGtqhJ3QGZd7iAHNEJeM=";
|
||||
|
||||
[Fact]
|
||||
public async Task GetAsync_WhenApiReturnsSuccess_ShouldDeserializeResponseContent()
|
||||
{
|
||||
// Arrange
|
||||
TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.OK, """[{"title":"Library One"}]"""));
|
||||
ApiHttpClient sut = CreateSut(messageHandler);
|
||||
|
||||
// Act
|
||||
Lumina.Presentation.Web.Common.DTO.Libraries.LibraryDto[] result = await sut.GetAsync<Lumina.Presentation.Web.Common.DTO.Libraries.LibraryDto[]>("libraries", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Single(result);
|
||||
Assert.Equal("Library One", result[0].Title);
|
||||
Assert.Equal(new Uri("http://localhost:5214/api/v1/libraries"), messageHandler.Requests[0].RequestUri);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAsync_WhenApiReturnsError_ShouldThrowApiExceptionWithProblemDetails()
|
||||
{
|
||||
// Arrange
|
||||
string problemDetailsJson = """
|
||||
{
|
||||
"type": "https://tools.ietf.org/html/rfc4918#section-11.2",
|
||||
"title": "General.Validation",
|
||||
"status": 422,
|
||||
"detail": "OneOrMoreValidationErrorsOccurred"
|
||||
}
|
||||
""";
|
||||
TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.UnprocessableEntity, problemDetailsJson));
|
||||
ApiHttpClient sut = CreateSut(messageHandler);
|
||||
|
||||
// Act
|
||||
ApiException exception = await Assert.ThrowsAsync<ApiException>(() => sut.GetAsync<object>("libraries", CancellationToken.None));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, exception.HttpStatusCode);
|
||||
Assert.NotNull(exception.ProblemDetails);
|
||||
Assert.Equal("General.Validation", exception.ProblemDetails!.Title);
|
||||
Assert.Equal(422, exception.ProblemDetails.Status);
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", exception.ProblemDetails.Detail);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAsync_WhenApiReturnsEmptyContent_ShouldReturnDefault()
|
||||
{
|
||||
// Arrange
|
||||
TestApiHttpMessageHandler messageHandler = new(_ => new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(string.Empty) });
|
||||
ApiHttpClient sut = CreateSut(messageHandler);
|
||||
|
||||
// Act
|
||||
object? result = await sut.GetAsync<object>("libraries", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAsync_WhenUserHasTokenClaim_ShouldSendAuthorizationHeader()
|
||||
{
|
||||
// Arrange
|
||||
TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.OK, "{}"));
|
||||
ApiHttpClient sut = CreateSut(messageHandler, token: "test-jwt-token");
|
||||
|
||||
// Act
|
||||
await sut.GetAsync<object>("libraries", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("Bearer", messageHandler.Requests[0].Headers.Authorization!.Scheme);
|
||||
Assert.Equal("test-jwt-token", messageHandler.Requests[0].Headers.Authorization!.Parameter);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PostAsync_WhenCalled_ShouldSerializePayloadAndDeserializeResponse()
|
||||
{
|
||||
// Arrange
|
||||
TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.OK, """{"success":true}"""));
|
||||
ApiHttpClient sut = CreateSut(messageHandler);
|
||||
|
||||
// Act
|
||||
SuccessResponse result = await sut.PostAsync<SuccessResponse, object>("auth/login", new { username = "testuser" }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.Success);
|
||||
Assert.Equal(HttpMethod.Post, messageHandler.Requests[0].Method);
|
||||
Assert.Equal("http://localhost:5214/api/v1/auth/login", messageHandler.Requests[0].RequestUri!.ToString());
|
||||
Assert.Contains("testuser", messageHandler.RequestBodies[0]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteAsync_WhenApiReturnsError_ShouldThrowApiException()
|
||||
{
|
||||
// Arrange
|
||||
TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.InternalServerError, """{"title":"General.Failure","status":500}"""));
|
||||
ApiHttpClient sut = CreateSut(messageHandler);
|
||||
|
||||
// Act
|
||||
ApiException exception = await Assert.ThrowsAsync<ApiException>(() => sut.DeleteAsync("libraries/1", CancellationToken.None));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.InternalServerError, exception.HttpStatusCode);
|
||||
Assert.Equal("/api/v1/libraries/1", exception.RequestPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetBlobAsync_WhenApiReturnsSuccess_ShouldReturnBlobData()
|
||||
{
|
||||
// Arrange
|
||||
byte[] imageBytes = Encoding.UTF8.GetBytes("fake-image-bytes");
|
||||
TestApiHttpMessageHandler messageHandler = new(_ =>
|
||||
{
|
||||
HttpResponseMessage response = new(HttpStatusCode.OK) { Content = new ByteArrayContent(imageBytes) };
|
||||
response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/png");
|
||||
return response;
|
||||
});
|
||||
ApiHttpClient sut = CreateSut(messageHandler);
|
||||
|
||||
// Act
|
||||
BlobDataDto blob = await sut.GetBlobAsync("libraries/1/cover", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(imageBytes, blob.Data);
|
||||
Assert.Equal("image/png", blob.ContentType);
|
||||
}
|
||||
|
||||
private static ApiHttpClient CreateSut(TestApiHttpMessageHandler messageHandler, string? token = null)
|
||||
{
|
||||
HttpClient httpClient = new(messageHandler);
|
||||
IHttpContextAccessor httpContextAccessor = Substitute.For<IHttpContextAccessor>();
|
||||
if (token is not null)
|
||||
{
|
||||
DefaultHttpContext httpContext = new();
|
||||
httpContext.User = new ClaimsPrincipal(new ClaimsIdentity([new Claim("Token", token)], "TestAuthentication"));
|
||||
httpContextAccessor.HttpContext.Returns(httpContext);
|
||||
}
|
||||
IOptionsSnapshot<ServerConfigurationDto> serverConfigurationOptions = Substitute.For<IOptionsSnapshot<ServerConfigurationDto>>();
|
||||
serverConfigurationOptions.Value.Returns(new ServerConfigurationDto { ApiVersion = '1', BaseAddress = "http://localhost", Port = 5214 });
|
||||
return new ApiHttpClient(httpClient, httpContextAccessor, serverConfigurationOptions);
|
||||
}
|
||||
|
||||
private static HttpResponseMessage CreateJsonResponse(HttpStatusCode statusCode, string json)
|
||||
{
|
||||
return new HttpResponseMessage(statusCode)
|
||||
{
|
||||
Content = new StringContent(json, Encoding.UTF8, "application/json")
|
||||
};
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Authorization;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Common.Authorization;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="AuthorizationPolicies"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AuthorizationPoliciesTests
|
||||
{
|
||||
[Fact]
|
||||
public void PolicyNames_WhenRead_ShouldMatchExpectedPolicyNames()
|
||||
{
|
||||
// Act & Assert
|
||||
Assert.Equal("RequireAdminRole", AuthorizationPolicies.REQUIRE_ADMIN_ROLE);
|
||||
Assert.Equal("RequireCreateLibrariesPermission", AuthorizationPolicies.REQUIRE_CREATE_LIBRARIES_PERMISSION);
|
||||
Assert.Equal("RequireInitialization", AuthorizationPolicies.REQUIRE_INITIALIZATION);
|
||||
}
|
||||
}
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.Authorization;
|
||||
using Lumina.Presentation.Web.Common.Enums.Authorization;
|
||||
using Lumina.Presentation.Web.Common.Responses.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Security.Claims;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Common.Authorization;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="AuthorizationService"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AuthorizationServiceTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly AuthorizationService _sut;
|
||||
private readonly Guid _userId;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AuthorizationServiceTests"/> class.
|
||||
/// </summary>
|
||||
public AuthorizationServiceTests()
|
||||
{
|
||||
_userId = Guid.NewGuid();
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
IHttpContextAccessor httpContextAccessor = Substitute.For<IHttpContextAccessor>();
|
||||
DefaultHttpContext httpContext = new();
|
||||
httpContext.User = new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, _userId.ToString())], "TestAuthentication"));
|
||||
httpContextAccessor.HttpContext.Returns(httpContext);
|
||||
_sut = new AuthorizationService(_mockApiHttpClient, httpContextAccessor);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HasPermissionAsync_WhenUserHasPermission_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
_mockApiHttpClient.GetAsync<GetAuthorizationResponse>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new GetAuthorizationResponse(_userId, "Admin", [AuthorizationPermission.CanCreateLibraries]));
|
||||
|
||||
// Act
|
||||
bool result = await _sut.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HasPermissionAsync_WhenUserDoesNotHavePermission_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
_mockApiHttpClient.GetAsync<GetAuthorizationResponse>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new GetAuthorizationResponse(_userId, "Admin", [AuthorizationPermission.CanViewUsers]));
|
||||
|
||||
// Act
|
||||
bool result = await _sut.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task IsInRoleAsync_WhenRoleMatches_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
_mockApiHttpClient.GetAsync<GetAuthorizationResponse>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new GetAuthorizationResponse(_userId, "Admin", []));
|
||||
|
||||
// Act
|
||||
bool result = await _sut.IsInRoleAsync("Admin", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task IsInRoleAsync_WhenRoleDoesNotMatch_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
_mockApiHttpClient.GetAsync<GetAuthorizationResponse>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new GetAuthorizationResponse(_userId, "User", []));
|
||||
|
||||
// Act
|
||||
bool result = await _sut.IsInRoleAsync("Admin", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HasPermissionAsync_WhenCalled_ShouldRequestAuthorizationForCurrentUser()
|
||||
{
|
||||
// Arrange
|
||||
_mockApiHttpClient.GetAsync<GetAuthorizationResponse>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new GetAuthorizationResponse(_userId, "Admin", []));
|
||||
|
||||
// Act
|
||||
await _sut.HasPermissionAsync(AuthorizationPermission.CanViewUsers, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<GetAuthorizationResponse>(
|
||||
Arg.Is<string>(endpoint => endpoint.StartsWith($"auth/get-authorization?userId={_userId}", StringComparison.OrdinalIgnoreCase)),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Localization;
|
||||
using Microsoft.AspNetCore.Mvc.Localization;
|
||||
using Microsoft.Extensions.Localization;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Common.Localization;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="CoreHtmlLocalizerFactory"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class CoreHtmlLocalizerFactoryTests
|
||||
{
|
||||
private readonly IStringLocalizerFactory _mockStringLocalizerFactory;
|
||||
private readonly CoreHtmlLocalizerFactory _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CoreHtmlLocalizerFactoryTests"/> class.
|
||||
/// </summary>
|
||||
public CoreHtmlLocalizerFactoryTests()
|
||||
{
|
||||
_mockStringLocalizerFactory = Substitute.For<IStringLocalizerFactory>();
|
||||
_mockStringLocalizerFactory.Create(Arg.Any<string>(), Arg.Any<string>()).Returns(Substitute.For<IStringLocalizer>());
|
||||
_sut = new CoreHtmlLocalizerFactory(_mockStringLocalizerFactory);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenBaseNameStartsWithLocationCorePrefix_ShouldStripCoreSegment()
|
||||
{
|
||||
// Act
|
||||
IHtmlLocalizer localizer = _sut.Create("Lumina.Presentation.Web.Core.Views.Auth.Login", "Lumina.Presentation.Web");
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(localizer);
|
||||
_mockStringLocalizerFactory.Received(1).Create("Lumina.Presentation.Web.Views.Auth.Login", "Lumina.Presentation.Web");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenBaseNameDoesNotStartWithLocationCorePrefix_ShouldKeepBaseNameUnchanged()
|
||||
{
|
||||
// Act
|
||||
IHtmlLocalizer localizer = _sut.Create("Lumina.Presentation.Web.Views.Shared.Layout", "Lumina.Presentation.Web");
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(localizer);
|
||||
_mockStringLocalizerFactory.Received(1).Create("Lumina.Presentation.Web.Views.Shared.Layout", "Lumina.Presentation.Web");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenResourceSourceTypeProvided_ShouldCreateLocalizerForType()
|
||||
{
|
||||
// Arrange
|
||||
_mockStringLocalizerFactory.Create(Arg.Any<Type>()).Returns(Substitute.For<IStringLocalizer>());
|
||||
|
||||
// Act
|
||||
IHtmlLocalizer localizer = _sut.Create(typeof(TestLocalizationResource));
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(localizer);
|
||||
_mockStringLocalizerFactory.Received(1).Create(typeof(TestLocalizationResource));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Marker type used for the resource source based localizer creation test.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
private sealed class TestLocalizationResource
|
||||
{
|
||||
}
|
||||
}
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Configuration;
|
||||
using Lumina.Presentation.Web.Common.Security;
|
||||
using Microsoft.Extensions.Options;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Common.Security;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="CryptographyService"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class CryptographyServiceTests
|
||||
{
|
||||
private const string TEST_ENCRYPTION_KEY = "FLYO0QRo6u2VzoFOgNkkEwYNGtqhJ3QGZd7iAHNEJeM=";
|
||||
private readonly CryptographyService _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CryptographyServiceTests"/> class.
|
||||
/// </summary>
|
||||
public CryptographyServiceTests()
|
||||
{
|
||||
EncryptionSettingsDto settings = new() { SecretKey = TEST_ENCRYPTION_KEY };
|
||||
_sut = new CryptographyService(Options.Create(settings));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Encrypt_WhenCalled_ShouldReturnCiphertextThatDecryptsToPlaintext()
|
||||
{
|
||||
// Arrange
|
||||
const string plaintext = "sensitive-data";
|
||||
|
||||
// Act
|
||||
string ciphertext = _sut.Encrypt(plaintext);
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(plaintext, ciphertext);
|
||||
Assert.Equal(plaintext, _sut.Decrypt(ciphertext));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Encrypt_WhenCalledTwice_ShouldReturnDifferentCiphertexts()
|
||||
{
|
||||
// Arrange
|
||||
const string plaintext = "sensitive-data";
|
||||
|
||||
// Act
|
||||
string firstCiphertext = _sut.Encrypt(plaintext);
|
||||
string secondCiphertext = _sut.Encrypt(plaintext);
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(firstCiphertext, secondCiphertext);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)]
|
||||
[InlineData("")]
|
||||
public void Encrypt_WhenPlaintextIsNullOrEmpty_ShouldThrowArgumentException(string? plaintext)
|
||||
{
|
||||
// Act
|
||||
ArgumentException exception = Assert.Throws<ArgumentException>(() => _sut.Encrypt(plaintext!));
|
||||
|
||||
// Assert
|
||||
Assert.Equal("plaintext", exception.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Decrypt_WhenCiphertextIsNotValidBase64_ShouldThrowFormatException()
|
||||
{
|
||||
// Act
|
||||
FormatException exception = Assert.Throws<FormatException>(() => _sut.Decrypt("not-valid-base64!!!"));
|
||||
|
||||
// Assert
|
||||
Assert.Contains("Base-64", exception.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Decrypt_WhenCiphertextIsTooShort_ShouldThrowArgumentException()
|
||||
{
|
||||
// Act
|
||||
ArgumentException exception = Assert.Throws<ArgumentException>(() => _sut.Decrypt(Convert.ToBase64String([1, 2, 3])));
|
||||
|
||||
// Assert
|
||||
Assert.Equal("Invalid ciphertext", exception.Message);
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Services;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Common.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ScriptIdentifierHelper"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ScriptIdentifierHelperTests
|
||||
{
|
||||
[Fact]
|
||||
public void GenerateScriptId_WhenCalled_ShouldReturnScriptPrefixedIdentifier()
|
||||
{
|
||||
// Act
|
||||
string scriptId = ScriptIdentifierHelper.GenerateScriptId();
|
||||
|
||||
// Assert
|
||||
Assert.StartsWith("script_", scriptId);
|
||||
Assert.True(Guid.TryParse(scriptId.AsSpan("script_".Length), out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GenerateScriptId_WhenCalledTwice_ShouldReturnDistinctIdentifiers()
|
||||
{
|
||||
// Act
|
||||
string firstScriptId = ScriptIdentifierHelper.GenerateScriptId();
|
||||
string secondScriptId = ScriptIdentifierHelper.GenerateScriptId();
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(firstScriptId, secondScriptId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ClearIdentifier_WhenCalledWithGeneratedIdentifier_ShouldNotThrow()
|
||||
{
|
||||
// Arrange
|
||||
string scriptId = ScriptIdentifierHelper.GenerateScriptId();
|
||||
|
||||
// Act
|
||||
ScriptIdentifierHelper.ClearIdentifier(scriptId);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(scriptId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Common.Services;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Common.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="UrlService"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UrlServiceTests
|
||||
{
|
||||
private readonly IHttpContextAccessor _mockHttpContextAccessor;
|
||||
private readonly UrlService _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UrlServiceTests"/> class.
|
||||
/// </summary>
|
||||
public UrlServiceTests()
|
||||
{
|
||||
_mockHttpContextAccessor = Substitute.For<IHttpContextAccessor>();
|
||||
_sut = new UrlService(_mockHttpContextAccessor);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetAbsoluteUrl_WhenRouteTemplateIsNotDefined_ShouldThrowArgumentException()
|
||||
{
|
||||
// Act
|
||||
ArgumentException exception = Assert.Throws<ArgumentException>(() => _sut.GetAbsoluteUrl("/not-a-real-route"));
|
||||
|
||||
// Assert
|
||||
Assert.Contains("not defined in the WebRoutes constants", exception.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetAbsoluteUrl_WhenHttpContextIsNull_ShouldReturnNull()
|
||||
{
|
||||
// Arrange
|
||||
_mockHttpContextAccessor.HttpContext.Returns((HttpContext?)null);
|
||||
|
||||
// Act
|
||||
string? url = _sut.GetAbsoluteUrl(WebRoutes.Authentication.LOGIN);
|
||||
|
||||
// Assert
|
||||
Assert.Null(url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetAbsoluteUrl_WhenCalled_ShouldReplaceCulturePlaceholderAndBuildAbsoluteUrl()
|
||||
{
|
||||
// Arrange
|
||||
DefaultHttpContext httpContext = CreateHttpContext(culture: "en-us", pathBase: "", host: "localhost:5012", scheme: "http");
|
||||
_mockHttpContextAccessor.HttpContext.Returns(httpContext);
|
||||
|
||||
// Act
|
||||
string? url = _sut.GetAbsoluteUrl(WebRoutes.Authentication.LOGIN);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("http://localhost:5012/en-us/auth/api-login", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetAbsoluteUrl_WhenCalledWithAdditionalRouteValues_ShouldReplacePlaceholders()
|
||||
{
|
||||
// Arrange
|
||||
DefaultHttpContext httpContext = CreateHttpContext(culture: "en-us", pathBase: "", host: "localhost:5012", scheme: "http");
|
||||
_mockHttpContextAccessor.HttpContext.Returns(httpContext);
|
||||
Guid id = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
string? url = _sut.GetAbsoluteUrl(WebRoutes.LibraryManagement.DELETE_LIBRARY, new { id });
|
||||
|
||||
// Assert
|
||||
Assert.Equal($"http://localhost:5012/en-us/libraries/manage/api-item/{id}", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetAbsoluteUrl_WhenPathBaseIsPresent_ShouldIncludePathBase()
|
||||
{
|
||||
// Arrange
|
||||
DefaultHttpContext httpContext = CreateHttpContext(culture: "de-de", pathBase: "/lumina", host: "localhost:5012", scheme: "https");
|
||||
_mockHttpContextAccessor.HttpContext.Returns(httpContext);
|
||||
|
||||
// Act
|
||||
string? url = _sut.GetAbsoluteUrl(WebRoutes.Authentication.REGISTER_VIEW);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("https://localhost:5012/lumina/de-de/auth/register", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetAbsoluteUrl_WhenRouteTemplateDoesNotStartWithSlash_ShouldPrependSlash()
|
||||
{
|
||||
// Arrange
|
||||
DefaultHttpContext httpContext = CreateHttpContext(culture: "en-us", pathBase: "", host: "localhost:5012", scheme: "http");
|
||||
_mockHttpContextAccessor.HttpContext.Returns(httpContext);
|
||||
|
||||
// Act
|
||||
string? url = _sut.GetAbsoluteUrl(WebRoutes.FileSystem.GET_TYPE);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("http://localhost:5012/file-system/api-get-type", url);
|
||||
}
|
||||
|
||||
private static DefaultHttpContext CreateHttpContext(string culture, string pathBase, string host, string scheme)
|
||||
{
|
||||
DefaultHttpContext httpContext = new();
|
||||
httpContext.Request.RouteValues["culture"] = culture;
|
||||
httpContext.Request.PathBase = pathBase;
|
||||
httpContext.Request.Host = new HostString(host);
|
||||
httpContext.Request.Scheme = scheme;
|
||||
return httpContext;
|
||||
}
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentValidation;
|
||||
using FluentValidation.Results;
|
||||
using Lumina.Presentation.Web.Common.DTO.Configuration;
|
||||
using Lumina.Presentation.Web.Common.Validators;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Common.Validators;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="EncryptionSettingsModelValidator"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class EncryptionSettingsModelValidatorTests
|
||||
{
|
||||
private const string VALID_BASE64_KEY = "FLYO0QRo6u2VzoFOgNkkEwYNGtqhJ3QGZd7iAHNEJeM=";
|
||||
private readonly EncryptionSettingsModelValidator _validator = new();
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenSecretKeyIsEmpty_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
EncryptionSettingsDto settings = new() { SecretKey = string.Empty };
|
||||
|
||||
// Act
|
||||
ValidationResult result = _validator.Validate(settings);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsValid);
|
||||
Assert.Contains(result.Errors, error => error.PropertyName == nameof(EncryptionSettingsDto.SecretKey) && error.ErrorMessage == "Encryption secret key cannot be empty!");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenSecretKeyIsNotBase64_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
EncryptionSettingsDto settings = new() { SecretKey = "not-base64-key!" };
|
||||
|
||||
// Act
|
||||
ValidationResult result = _validator.Validate(settings);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsValid);
|
||||
Assert.Contains(result.Errors, error => error.PropertyName == nameof(EncryptionSettingsDto.SecretKey) && error.ErrorMessage == "Encryption secret key must be a base64 string!");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenSecretKeyIsValidBase64_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
EncryptionSettingsDto settings = new() { SecretKey = VALID_BASE64_KEY };
|
||||
|
||||
// Act
|
||||
ValidationResult result = _validator.Validate(settings);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsValid);
|
||||
}
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentValidation;
|
||||
using FluentValidation.Results;
|
||||
using Lumina.Presentation.Web.Common.DTO.Configuration;
|
||||
using Lumina.Presentation.Web.Common.Validators;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Common.Validators;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ServerConfigurationModelValidator"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ServerConfigurationModelValidatorTests
|
||||
{
|
||||
private readonly ServerConfigurationModelValidator _validator = new();
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenBaseAddressIsEmpty_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
ServerConfigurationDto configuration = new() { ApiVersion = '1', BaseAddress = string.Empty, Port = 5214 };
|
||||
|
||||
// Act
|
||||
ValidationResult result = _validator.Validate(configuration);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsValid);
|
||||
Assert.Contains(result.Errors, error => error.PropertyName == nameof(ServerConfigurationDto.BaseAddress) && error.ErrorMessage == "Base address cannot be empty!");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData((ushort)0)] // minimum allowed value
|
||||
[InlineData((ushort)65535)] // maximum allowed value
|
||||
public void Validate_WhenPortIsAtBoundary_ShouldNotHaveValidationError(ushort port)
|
||||
{
|
||||
// Arrange
|
||||
ServerConfigurationDto configuration = new() { ApiVersion = '1', BaseAddress = "http://localhost", Port = port };
|
||||
|
||||
// Act
|
||||
ValidationResult result = _validator.Validate(configuration);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsValid);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData((char)0)] // minimum allowed API version
|
||||
[InlineData((char)255)] // maximum allowed API version
|
||||
public void Validate_WhenApiVersionIsAtBoundary_ShouldNotHaveValidationError(char apiVersion)
|
||||
{
|
||||
// Arrange
|
||||
ServerConfigurationDto configuration = new() { ApiVersion = apiVersion, BaseAddress = "http://localhost", Port = 5214 };
|
||||
|
||||
// Act
|
||||
ValidationResult result = _validator.Validate(configuration);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsValid);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenConfigurationIsValid_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
ServerConfigurationDto configuration = new() { ApiVersion = '1', BaseAddress = "http://localhost", Port = 5214 };
|
||||
|
||||
// Act
|
||||
ValidationResult result = _validator.Validate(configuration);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsValid);
|
||||
}
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.Authorization;
|
||||
using Lumina.Presentation.Web.Common.Enums.Authorization;
|
||||
using Lumina.Presentation.Web.Common.Requests.Authorization;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Admin.Authorization.Roles.AddRole;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Authorization;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Admin.Authorization.Roles.AddRole;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="AddRoleEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddRoleEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly AddRoleEndpoint _sut;
|
||||
private readonly AddRoleRequestFixture _addRoleRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddRoleEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public AddRoleEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<AddRoleEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldCreateRoleViaApiAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
AddRoleRequest request = _addRoleRequestFixture.Create();
|
||||
RolePermissionsDto expectedResponse = new(new RoleDto(Guid.NewGuid(), request.RoleName!), [new PermissionDto(Guid.NewGuid(), AuthorizationPermission.CanViewUsers)]);
|
||||
_mockApiHttpClient.PostAsync<RolePermissionsDto, AddRoleRequest>(Arg.Any<string>(), Arg.Any<AddRoleRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedResponse);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostAsync<RolePermissionsDto, AddRoleRequest>(
|
||||
ApiRoutes.Roles.CREATE_ROLE,
|
||||
Arg.Is<AddRoleRequest>(role => role.RoleName == request.RoleName && role.Permissions!.SequenceEqual(request.Permissions!)),
|
||||
Arg.Any<CancellationToken>());
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
}
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.Requests.Authorization;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Admin.Authorization.Roles.DeleteRole;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Authorization;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Admin.Authorization.Roles.DeleteRole;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="DeleteRoleEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteRoleEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly DeleteRoleEndpoint _sut;
|
||||
private readonly DeleteRoleRequestFixture _deleteRoleRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteRoleEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public DeleteRoleEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<DeleteRoleEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldDeleteRoleViaApiAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
DeleteRoleRequest request = _deleteRoleRequestFixture.Create();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
string expectedEndpoint = ApiRoutes.Roles.DELETE_ROLE.Replace("{roleId}", request.RoleId.ToString());
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(expectedEndpoint, Arg.Any<CancellationToken>());
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
}
|
||||
}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.Authorization;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Admin.Authorization.Roles.GetRoles;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Authorization;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Admin.Authorization.Roles.GetRoles;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetRolesEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetRolesEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly GetRolesEndpoint _sut;
|
||||
private readonly RoleDtoFixture _roleDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetRolesEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetRolesEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<GetRolesEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsRoles_ShouldReturnSuccessJsonWithRoles()
|
||||
{
|
||||
// Arrange
|
||||
RoleDto[] expectedRoles = [.. _roleDtoFixture.CreateMany(2)];
|
||||
_mockApiHttpClient.GetAsync<RoleDto[]>(ApiRoutes.Roles.GET_ROLES, Arg.Any<CancellationToken>())
|
||||
.Returns(expectedRoles);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
RoleDto[]? returnedRoles = jsonDocument.RootElement.GetProperty("data").Deserialize<RoleDto[]>(CreateCaseInsensitiveOptions());
|
||||
Assert.Equal(expectedRoles.Select(role => role.RoleName), returnedRoles!.Select(role => role.RoleName));
|
||||
}
|
||||
|
||||
private static JsonSerializerOptions CreateCaseInsensitiveOptions()
|
||||
{
|
||||
return new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldRequestRolesFromApi()
|
||||
{
|
||||
// Arrange
|
||||
_mockApiHttpClient.GetAsync<RoleDto[]>(ApiRoutes.Roles.GET_ROLES, Arg.Any<CancellationToken>())
|
||||
.Returns([.. _roleDtoFixture.CreateMany(2)]);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<RoleDto[]>(ApiRoutes.Roles.GET_ROLES, Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Http;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.Fixtures.Core.Endpoints.Common;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="Lumina.Presentation.Web.Core.Endpoints.Common.BaseEndpoint"/> class.
|
||||
/// </summary>
|
||||
public class BaseEndpointTests
|
||||
{
|
||||
private readonly BaseEndpointFixture _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="BaseEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public BaseEndpointTests()
|
||||
{
|
||||
_sut = Factory.Create<BaseEndpointFixture>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TestJsonSuccess_WhenCalledWithData_ShouldReturnSuccessJsonEnvelopeWithData()
|
||||
{
|
||||
// Act
|
||||
IResult result = _sut.TestJsonSuccess(new { itemId = "test-id" });
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal("test-id", jsonDocument.RootElement.GetProperty("data").GetProperty("itemId").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TestJsonSuccess_WhenCalledWithoutData_ShouldReturnSuccessJsonEnvelope()
|
||||
{
|
||||
// Act
|
||||
IResult result = _sut.TestJsonSuccess();
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.False(jsonDocument.RootElement.TryGetProperty("data", out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TestView_WhenCalled_ShouldReturnRazorViewResult()
|
||||
{
|
||||
// Arrange
|
||||
TestHttpContextFactory.ConfigureSession(_sut.HttpContext, TestHttpContextFactory.CreateSession());
|
||||
_sut.HttpContext.Request.Path = "/en-us/home";
|
||||
|
||||
// Act
|
||||
IResult result = _sut.TestView("/Core/Views/Home/Index.cshtml");
|
||||
|
||||
// Assert
|
||||
Assert.IsType<RazorViewResult>(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TestView_WhenCalled_ShouldStoreLastDisplayedViewInSession()
|
||||
{
|
||||
// Arrange
|
||||
Microsoft.AspNetCore.Http.ISession session = TestHttpContextFactory.CreateSession();
|
||||
TestHttpContextFactory.ConfigureSession(_sut.HttpContext, session);
|
||||
_sut.HttpContext.Request.Path = "/en-us/libraries/manage";
|
||||
|
||||
// Act
|
||||
_sut.TestView("/Core/Views/Library/Management/Index.cshtml");
|
||||
|
||||
// Assert
|
||||
session.Received(1).Set(HttpContextItemKeys.LAST_DISPLAYED_VIEW, Arg.Any<byte[]>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TestCulture_WhenCultureRouteValuePresent_ShouldReturnCulture()
|
||||
{
|
||||
// Arrange
|
||||
TestHttpContextFactory.ConfigureCulture(_sut.HttpContext, "de-DE");
|
||||
|
||||
// Act
|
||||
string culture = _sut.TestCulture;
|
||||
|
||||
// Assert
|
||||
Assert.Equal("de-DE", culture);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TestCulture_WhenCultureRouteValueMissing_ShouldReturnDefaultCulture()
|
||||
{
|
||||
// Arrange
|
||||
TestHttpContextFactory.ConfigureCulture(_sut.HttpContext, null);
|
||||
|
||||
// Act
|
||||
string culture = _sut.TestCulture;
|
||||
|
||||
// Assert
|
||||
Assert.Equal("en-US", culture);
|
||||
}
|
||||
}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.FileSystemManagement;
|
||||
using Lumina.Presentation.Web.Common.Requests.FileSystemManagement.Directories;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Directories.GetDirectories;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.FileSystemManagement.Directories;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.FileSystemManagement.Directories.GetDirectories;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetDirectoriesEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetDirectoriesEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly GetDirectoriesEndpoint _sut;
|
||||
private readonly GetDirectoriesRequestFixture _getDirectoriesRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetDirectoriesEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetDirectoriesEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<GetDirectoriesEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsDirectories_ShouldReturnSuccessJsonWithDirectories()
|
||||
{
|
||||
// Arrange
|
||||
GetDirectoriesRequest request = _getDirectoriesRequestFixture.Create(path: "/media", includeHiddenElements: true);
|
||||
DirectoryDto[] expectedDirectories = [new DirectoryDto { Path = "/media/books", Name = "books" }];
|
||||
_mockApiHttpClient.GetAsync<DirectoryDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedDirectories);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
string expectedEndpoint = $"{ApiRoutes.Directories.GET_DIRECTORIES}?path={Uri.EscapeDataString(request.Path!)}&includeHiddenElements=True";
|
||||
await _mockApiHttpClient.Received(1).GetAsync<DirectoryDto[]>(expectedEndpoint, Arg.Any<CancellationToken>());
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(1, jsonDocument.RootElement.GetProperty("data").GetArrayLength());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalledWithoutHiddenElements_ShouldRequestWithoutHiddenElementsFlag()
|
||||
{
|
||||
// Arrange
|
||||
GetDirectoriesRequest request = _getDirectoriesRequestFixture.Create(path: "/media", includeHiddenElements: false);
|
||||
_mockApiHttpClient.GetAsync<DirectoryDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns([]);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
string expectedEndpoint = $"{ApiRoutes.Directories.GET_DIRECTORIES}?path={Uri.EscapeDataString(request.Path!)}&includeHiddenElements=False";
|
||||
await _mockApiHttpClient.Received(1).GetAsync<DirectoryDto[]>(expectedEndpoint, Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.FileSystemManagement;
|
||||
using Lumina.Presentation.Web.Common.Requests.FileSystemManagement.Path;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Path.ValidatePath;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.FileSystemManagement.Path;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.FileSystemManagement.Path.ValidatePath;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ValidatePathEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ValidatePathEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly ValidatePathEndpoint _sut;
|
||||
private readonly ValidatePathRequestFixture _validatePathRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ValidatePathEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public ValidatePathEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<ValidatePathEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiValidatesPath_ShouldReturnSuccessJsonWithIsValid()
|
||||
{
|
||||
// Arrange
|
||||
ValidatePathRequest request = _validatePathRequestFixture.Create(path: "/media/books");
|
||||
_mockApiHttpClient.GetAsync<PathValidDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new PathValidDto(true));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
string expectedEndpoint = $"{ApiRoutes.Path.VALIDATE}?path={Uri.EscapeDataString(request.Path!)}";
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PathValidDto>(expectedEndpoint, Arg.Any<CancellationToken>());
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("data").GetProperty("isValid").GetBoolean());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenPathIsInvalid_ShouldReturnSuccessJsonWithIsValidFalse()
|
||||
{
|
||||
// Arrange
|
||||
ValidatePathRequest request = _validatePathRequestFixture.Create(path: "C:/invalid|path");
|
||||
_mockApiHttpClient.GetAsync<PathValidDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new PathValidDto(false));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.False(jsonDocument.RootElement.GetProperty("data").GetProperty("isValid").GetBoolean());
|
||||
}
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.Management;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.DeleteLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Management;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.Management.DeleteLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="DeleteLibraryEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteLibraryEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly DeleteLibraryEndpoint _sut;
|
||||
private readonly DeleteLibraryRequestFixture _deleteLibraryRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteLibraryEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public DeleteLibraryEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<DeleteLibraryEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldDeleteLibraryViaApiAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
DeleteLibraryRequest request = _deleteLibraryRequestFixture.Create();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
string expectedEndpoint = ApiRoutes.Libraries.DELETE_LIBRARY.Replace("{id}", request.Id.ToString());
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(expectedEndpoint, Arg.Any<CancellationToken>());
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
}
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraries;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.Management.GetLibraries;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetLibrariesEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetLibrariesEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly GetLibrariesEndpoint _sut;
|
||||
private readonly LibraryDtoFixture _libraryDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetLibrariesEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetLibrariesEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<GetLibrariesEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsLibraries_ShouldReturnSuccessJsonWithLibraries()
|
||||
{
|
||||
// Arrange
|
||||
LibraryDto[] expectedLibraries = [.. _libraryDtoFixture.CreateMany(2)];
|
||||
_mockApiHttpClient.GetAsync<LibraryDto[]>(ApiRoutes.Libraries.GET_LIBRARIES, Arg.Any<CancellationToken>())
|
||||
.Returns(expectedLibraries);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
LibraryDto[]? returnedLibraries = jsonDocument.RootElement.GetProperty("data").Deserialize<LibraryDto[]>(new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
|
||||
Assert.Equal(expectedLibraries.Select(library => library.Title), returnedLibraries!.Select(library => library.Title));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldRequestLibrariesFromApi()
|
||||
{
|
||||
// Arrange
|
||||
_mockApiHttpClient.GetAsync<LibraryDto[]>(ApiRoutes.Libraries.GET_LIBRARIES, Arg.Any<CancellationToken>())
|
||||
.Returns([.. _libraryDtoFixture.CreateMany(2)]);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<LibraryDto[]>(ApiRoutes.Libraries.GET_LIBRARIES, Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.SaveLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.Management.SaveLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="SaveLibraryEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SaveLibraryEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly SaveLibraryEndpoint _sut;
|
||||
private readonly LibraryDtoFixture _libraryDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SaveLibraryEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public SaveLibraryEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<SaveLibraryEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRequestHasId_ShouldUpdateLibraryViaApi()
|
||||
{
|
||||
// Arrange
|
||||
LibraryDto request = _libraryDtoFixture.Create();
|
||||
LibraryDto expectedResponse = _libraryDtoFixture.Create(id: request.Id);
|
||||
_mockApiHttpClient.PutAsync<LibraryDto, LibraryDto>(Arg.Any<string>(), Arg.Any<LibraryDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedResponse);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
string expectedEndpoint = ApiRoutes.Libraries.UPDATE_LIBRARY.Replace("{id}", request.Id!.Value.ToString());
|
||||
await _mockApiHttpClient.Received(1).PutAsync<LibraryDto, LibraryDto>(expectedEndpoint, Arg.Is<LibraryDto>(library => library.Title == request.Title), Arg.Any<CancellationToken>());
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRequestHasNoId_ShouldCreateLibraryViaApi()
|
||||
{
|
||||
// Arrange
|
||||
LibraryDto request = _libraryDtoFixture.Create();
|
||||
request.Id = null;
|
||||
LibraryDto expectedResponse = _libraryDtoFixture.Create(id: request.Id);
|
||||
_mockApiHttpClient.PostAsync<LibraryDto, LibraryDto>(Arg.Any<string>(), Arg.Any<LibraryDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedResponse);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostAsync<LibraryDto, LibraryDto>(ApiRoutes.Libraries.ADD_LIBRARY, Arg.Is<LibraryDto>(library => library.Title == request.Title), Arg.Any<CancellationToken>());
|
||||
await _mockApiHttpClient.DidNotReceive().PutAsync<LibraryDto, LibraryDto>(Arg.Any<string>(), Arg.Any<LibraryDto>(), Arg.Any<CancellationToken>());
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
}
|
||||
}
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Common.Enums.Common;
|
||||
using Lumina.Presentation.Web.Common.Requests.Libraries;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetLibraryItems;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Libraries;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetLibraryItems;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetLibraryItemsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetLibraryItemsEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly GetLibraryItemsEndpoint _sut;
|
||||
private readonly GetBooksLiteRequestFixture _getBooksLiteRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetLibraryItemsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetLibraryItemsEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<GetLibraryItemsEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldRequestLibraryItemsWithQueryParameters()
|
||||
{
|
||||
// Arrange
|
||||
GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create(
|
||||
currentPage: 2,
|
||||
perPage: 48,
|
||||
searchTerm: "the hobbit",
|
||||
filterAlphaKey: "H",
|
||||
ignoreThePrefixForAlphaPicker: true,
|
||||
sortBy: "title",
|
||||
sortOrder: SortOrder.Ascending);
|
||||
_mockApiHttpClient.GetAsync<PaginatedBookLiteDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new PaginatedBookLiteDto());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedBookLiteDto>(
|
||||
Arg.Is<string>(endpoint =>
|
||||
endpoint.StartsWith(ApiRoutes.Books.GET_BOOKS_LITE, StringComparison.OrdinalIgnoreCase) &&
|
||||
endpoint.Contains($"libraryId={request.LibraryId}") &&
|
||||
endpoint.Contains("currentPage=2") &&
|
||||
endpoint.Contains("perPage=48") &&
|
||||
endpoint.Contains("searchTerm=the%20hobbit") &&
|
||||
endpoint.Contains("filterAlphaKey=H") &&
|
||||
endpoint.Contains("ignoreThePrefixForAlphaPicker=True") &&
|
||||
endpoint.Contains("sortBy=title") &&
|
||||
endpoint.Contains("sortOrder=Ascending")),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalledWithOnlyLibraryId_ShouldRequestWithoutOptionalParameters()
|
||||
{
|
||||
// Arrange
|
||||
GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create();
|
||||
_mockApiHttpClient.GetAsync<PaginatedBookLiteDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new PaginatedBookLiteDto());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedBookLiteDto>(
|
||||
Arg.Is<string>(endpoint =>
|
||||
endpoint.StartsWith(ApiRoutes.Books.GET_BOOKS_LITE, StringComparison.OrdinalIgnoreCase) &&
|
||||
endpoint.EndsWith($"libraryId={request.LibraryId}&ignoreThePrefixForAlphaPicker=False", StringComparison.OrdinalIgnoreCase) &&
|
||||
!endpoint.Contains("currentPage=") &&
|
||||
!endpoint.Contains("searchTerm=") &&
|
||||
!endpoint.Contains("sortBy=")),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsPaginatedItems_ShouldReturnSuccessJsonWithItems()
|
||||
{
|
||||
// Arrange
|
||||
GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create();
|
||||
PaginatedBookLiteDto expectedResponse = new()
|
||||
{
|
||||
CurrentPage = 1,
|
||||
PerPage = 48,
|
||||
Count = 1,
|
||||
NumberOfPages = 1,
|
||||
Data = [new BookLiteDto { Id = Guid.NewGuid(), Title = "Test Book" }]
|
||||
};
|
||||
_mockApiHttpClient.GetAsync<PaginatedBookLiteDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedResponse);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
JsonElement data = jsonDocument.RootElement.GetProperty("data");
|
||||
Assert.Equal(1, data.GetProperty("currentPage").GetInt32());
|
||||
Assert.Equal(1, data.GetProperty("data").GetArrayLength());
|
||||
}
|
||||
}
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Common.Http;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Common.Services;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Index;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Index;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="BooksIndexViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class BooksIndexViewEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly IUrlService _mockUrlService;
|
||||
private readonly BooksIndexViewEndpoint _sut;
|
||||
private readonly LibraryDtoFixture _libraryDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="BooksIndexViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public BooksIndexViewEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_mockUrlService = Substitute.For<IUrlService>();
|
||||
_sut = Factory.Create<BooksIndexViewEndpoint>(_mockApiHttpClient, _mockUrlService);
|
||||
TestHttpContextFactory.ConfigureSession(_sut.HttpContext, TestHttpContextFactory.CreateSession());
|
||||
_sut.HttpContext.Request.Path = "/en-us/library/written-content-library/books-library/books";
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenLibraryIdIsNull_ShouldRedirectToHome()
|
||||
{
|
||||
// Arrange
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Home.INDEX_CULTURED).Returns("http://localhost/en-us");
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(new GetBooksViewRequest(null), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
RedirectHttpResult redirectResult = Assert.IsType<RedirectHttpResult>(result);
|
||||
Assert.Equal("http://localhost/en-us", redirectResult.Url);
|
||||
await _mockApiHttpClient.DidNotReceive().GetAsync<LibraryDto>(Arg.Any<string>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenLibraryIdProvided_ShouldReturnRazorViewResultWithLibraryModel()
|
||||
{
|
||||
// Arrange
|
||||
LibraryDto expectedLibrary = _libraryDtoFixture.Create();
|
||||
_mockApiHttpClient.GetAsync<LibraryDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedLibrary);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(new GetBooksViewRequest(expectedLibrary.Id), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.IsType<RazorViewResult>(result);
|
||||
string expectedEndpoint = ApiRoutes.Libraries.GET_LIBRARY_BY_ID.Replace("{id}", expectedLibrary.Id!.Value.ToString());
|
||||
await _mockApiHttpClient.Received(1).GetAsync<LibraryDto>(expectedEndpoint, Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.Plugins;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Plugins.GetPlugins;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Plugins.GetPlugins;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetPluginsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetPluginsEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly GetPluginsEndpoint _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPluginsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetPluginsEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<GetPluginsEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsPlugins_ShouldReturnSuccessJsonWithPlugins()
|
||||
{
|
||||
// Arrange
|
||||
PluginDto[] expectedPlugins = [new PluginDto { Id = Guid.NewGuid(), Name = "OpenLibrary", Author = "Test Author", Version = "1.0.0" }];
|
||||
_mockApiHttpClient.GetAsync<PluginDto[]>(ApiRoutes.Plugins.GET_PLUGINS, Arg.Any<CancellationToken>())
|
||||
.Returns(expectedPlugins);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
PluginDto[]? returnedPlugins = jsonDocument.RootElement.GetProperty("data").Deserialize<PluginDto[]>(new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
|
||||
Assert.Equal(expectedPlugins.Select(plugin => plugin.Name), returnedPlugins!.Select(plugin => plugin.Name));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldRequestPluginsFromApi()
|
||||
{
|
||||
// Arrange
|
||||
_mockApiHttpClient.GetAsync<PluginDto[]>(ApiRoutes.Plugins.GET_PLUGINS, Arg.Any<CancellationToken>())
|
||||
.Returns([new PluginDto { Id = Guid.NewGuid(), Name = "OpenLibrary" }]);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PluginDto[]>(ApiRoutes.Plugins.GET_PLUGINS, Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.Requests.Plugins;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Plugins.UpdatePluginSettings;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Plugins.UpdatePluginSettings;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="UpdatePluginSettingsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdatePluginSettingsEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly UpdatePluginSettingsEndpoint _sut;
|
||||
private readonly UpdatePluginSettingsRequestFixture _updatePluginSettingsRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdatePluginSettingsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public UpdatePluginSettingsEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<UpdatePluginSettingsEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldUpdatePluginSettingsViaApiAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
UpdatePluginSettingsRequest request = _updatePluginSettingsRequestFixture.Create();
|
||||
_mockApiHttpClient.PutAsync<Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest, UpdatePluginSettingsRequest>(Arg.Any<string>(), Arg.Any<UpdatePluginSettingsRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest());
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
string expectedEndpoint = ApiRoutes.Plugins.UPDATE_PLUGIN_SETTINGS.Replace("{pluginId}", request.PluginId.ToString());
|
||||
await _mockApiHttpClient.Received(1).PutAsync<Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest, UpdatePluginSettingsRequest>(
|
||||
expectedEndpoint,
|
||||
Arg.Is<UpdatePluginSettingsRequest>(settings => settings.PluginId == request.PluginId),
|
||||
Arg.Any<CancellationToken>());
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
}
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Requests.Tools;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Common.Services;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Tools.Language.SetLanguage;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using Microsoft.AspNetCore.Localization;
|
||||
using NSubstitute;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Tools.Language.SetLanguage;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="SetLanguageEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SetLanguageEndpointTests
|
||||
{
|
||||
private readonly IUrlService _mockUrlService;
|
||||
private readonly SetLanguageEndpoint _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SetLanguageEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public SetLanguageEndpointTests()
|
||||
{
|
||||
_mockUrlService = Substitute.For<IUrlService>();
|
||||
_sut = Factory.Create<SetLanguageEndpoint>(_mockUrlService);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalledWithoutReturnUrl_ShouldSetCultureCookieAndRedirectWithNewCulture()
|
||||
{
|
||||
// Arrange
|
||||
TestHttpContextFactory.ConfigureCulture(_sut.HttpContext, "en-us");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Home.INDEX_CULTURED).Returns("http://localhost/en-us/");
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(new SetLanguageRequest("de-DE", null), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
RedirectHttpResult redirectResult = Assert.IsType<RedirectHttpResult>(result);
|
||||
Assert.Equal("http://localhost/de-de/", redirectResult.Url);
|
||||
Assert.True(redirectResult.AcceptLocalUrlOnly);
|
||||
string setCookieHeader = _sut.HttpContext.Response.Headers.SetCookie.ToString();
|
||||
Assert.Contains(CookieRequestCultureProvider.DefaultCookieName, setCookieHeader);
|
||||
Assert.Contains("de-DE", setCookieHeader);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenReturnUrlProvided_ShouldReplaceCultureInReturnUrl()
|
||||
{
|
||||
// Arrange
|
||||
TestHttpContextFactory.ConfigureCulture(_sut.HttpContext, "en-us");
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(new SetLanguageRequest("de-DE", "/en-us/tools/settings"), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
RedirectHttpResult redirectResult = Assert.IsType<RedirectHttpResult>(result);
|
||||
Assert.Equal("/de-de/tools/settings", redirectResult.Url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenPathBasePresent_ShouldKeepPathBaseInRedirectUrl()
|
||||
{
|
||||
// Arrange
|
||||
TestHttpContextFactory.ConfigureCulture(_sut.HttpContext, "en-us");
|
||||
_sut.HttpContext.Request.PathBase = "/lumina";
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(new SetLanguageRequest("fr-FR", "/en-us/tools/settings"), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
RedirectHttpResult redirectResult = Assert.IsType<RedirectHttpResult>(result);
|
||||
Assert.Equal("/lumina/fr-fr/tools/settings", redirectResult.Url);
|
||||
}
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.UsersManagement;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Tools.Settings.GetUserSettings;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.UsersManagement;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Tools.Settings.GetUserSettings;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetUserSettingsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetUserSettingsEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly GetUserSettingsEndpoint _sut;
|
||||
private readonly UserSettingsDtoFixture _userSettingsDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetUserSettingsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetUserSettingsEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<GetUserSettingsEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsSettings_ShouldReturnSuccessJsonWithSettings()
|
||||
{
|
||||
// Arrange
|
||||
UserSettingsDto expectedSettings = _userSettingsDtoFixture.Create();
|
||||
_mockApiHttpClient.GetAsync<UserSettingsDto>(ApiRoutes.Users.GET_USER_SETTINGS, Arg.Any<CancellationToken>())
|
||||
.Returns(expectedSettings);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
JsonElement data = jsonDocument.RootElement.GetProperty("data");
|
||||
Assert.Equal(expectedSettings.ItemsPerPage, data.GetProperty("itemsPerPage").GetInt32());
|
||||
Assert.Equal(expectedSettings.IsPaginationEnabled, data.GetProperty("isPaginationEnabled").GetBoolean());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldRequestUserSettingsFromApi()
|
||||
{
|
||||
// Arrange
|
||||
_mockApiHttpClient.GetAsync<UserSettingsDto>(ApiRoutes.Users.GET_USER_SETTINGS, Arg.Any<CancellationToken>())
|
||||
.Returns(_userSettingsDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<UserSettingsDto>(ApiRoutes.Users.GET_USER_SETTINGS, Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.UsersManagement;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Tools.Settings.UpdateUserSettings;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.UsersManagement;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Tools.Settings.UpdateUserSettings;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="UpdateUserSettingsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateUserSettingsEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly UpdateUserSettingsEndpoint _sut;
|
||||
private readonly UserSettingsDtoFixture _userSettingsDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateUserSettingsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public UpdateUserSettingsEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<UpdateUserSettingsEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldUpdateSettingsViaApiAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
UserSettingsDto request = _userSettingsDtoFixture.Create();
|
||||
_mockApiHttpClient.PutAsync<Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest, UserSettingsDto>(Arg.Any<string>(), Arg.Any<UserSettingsDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest());
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutAsync<Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest, UserSettingsDto>(
|
||||
ApiRoutes.Users.UPDATE_USER_SETTINGS,
|
||||
Arg.Is<UserSettingsDto>(settings => settings.ItemsPerPage == request.ItemsPerPage && settings.IsPaginationEnabled == request.IsPaginationEnabled),
|
||||
Arg.Any<CancellationToken>());
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("data").GetProperty("isUpdated").GetBoolean());
|
||||
}
|
||||
}
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Http;
|
||||
using Lumina.Presentation.Web.Common.Requests.UsersManagement.Authentication;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Common.Services;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.Login;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.UsersManagement.Authentication.Login;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="LoginViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LoginViewEndpointTests
|
||||
{
|
||||
private readonly IUrlService _mockUrlService;
|
||||
private readonly LoginViewEndpoint _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LoginViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public LoginViewEndpointTests()
|
||||
{
|
||||
_mockUrlService = Substitute.For<IUrlService>();
|
||||
_sut = Factory.Create<LoginViewEndpoint>(_mockUrlService);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenUserAlreadyAuthenticated_ShouldRedirectToHome()
|
||||
{
|
||||
// Arrange
|
||||
TestHttpContextFactory.ConfigureUser(_sut.HttpContext, TestHttpContextFactory.CreateAuthenticatedUser());
|
||||
TestHttpContextFactory.ConfigureSession(_sut.HttpContext, TestHttpContextFactory.CreateSession());
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Home.INDEX_CULTURED).Returns("http://localhost/en-us");
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(new LoginViewRequest(), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
RedirectHttpResult redirectResult = Assert.IsType<RedirectHttpResult>(result);
|
||||
Assert.Equal("http://localhost/en-us", redirectResult.Url);
|
||||
_mockUrlService.Received(1).GetAbsoluteUrl(WebRoutes.Home.INDEX_CULTURED);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuperAdminSetupPending_ShouldRedirectToRegisterView()
|
||||
{
|
||||
// Arrange
|
||||
Microsoft.AspNetCore.Http.ISession session = Substitute.For<Microsoft.AspNetCore.Http.ISession>();
|
||||
byte[] pendingBytes = Encoding.UTF8.GetBytes("true");
|
||||
#pragma warning disable CS8601 // possible null reference assignment in the NSubstitute out-argument stub
|
||||
session.TryGetValue(HttpContextItemKeys.PENDING_SUPER_ADMIN_SETUP, out Arg.Any<byte[]>()).Returns(callInfo =>
|
||||
{
|
||||
callInfo[1] = pendingBytes;
|
||||
return true;
|
||||
});
|
||||
#pragma warning restore CS8601
|
||||
TestHttpContextFactory.ConfigureSession(_sut.HttpContext, session);
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Authentication.REGISTER_VIEW).Returns("http://localhost/en-us/auth/register");
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(new LoginViewRequest(), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
RedirectHttpResult redirectResult = Assert.IsType<RedirectHttpResult>(result);
|
||||
Assert.Equal("http://localhost/en-us/auth/register", redirectResult.Url);
|
||||
_mockUrlService.Received(1).GetAbsoluteUrl(WebRoutes.Authentication.REGISTER_VIEW);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenNotAuthenticatedAndInitialized_ShouldReturnRazorViewResult()
|
||||
{
|
||||
// Arrange
|
||||
TestHttpContextFactory.ConfigureSession(_sut.HttpContext, TestHttpContextFactory.CreateSession());
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(new LoginViewRequest(), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.IsType<RazorViewResult>(result);
|
||||
}
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.Requests.UsersManagement;
|
||||
using Lumina.Presentation.Web.Common.Responses.UsersManagement;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.RecoverPassword;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.UsersManagement;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.UsersManagement.Authentication.RecoverPassword;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="RecoverPasswordEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RecoverPasswordEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly RecoverPasswordEndpoint _sut;
|
||||
private readonly RecoverPasswordRequestFixture _recoverPasswordRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RecoverPasswordEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public RecoverPasswordEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<RecoverPasswordEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldRecoverPasswordViaApiAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
RecoverPasswordRequest request = _recoverPasswordRequestFixture.Create();
|
||||
RecoverPasswordResponse expectedResponse = new(true);
|
||||
_mockApiHttpClient.PostAsync<RecoverPasswordResponse, RecoverPasswordRequest>(Arg.Any<string>(), Arg.Any<RecoverPasswordRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedResponse);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostAsync<RecoverPasswordResponse, RecoverPasswordRequest>(
|
||||
ApiRoutes.Authentication.RECOVER_PASSWORD,
|
||||
Arg.Is<RecoverPasswordRequest>(recovery => recovery.Username == request.Username),
|
||||
Arg.Any<CancellationToken>());
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("data").GetProperty("isPasswordReset").GetBoolean());
|
||||
}
|
||||
}
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.Requests.UsersManagement;
|
||||
using Lumina.Presentation.Web.Common.Responses.UsersManagement;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.Register;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.UsersManagement;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.UsersManagement.Authentication.Register;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="RegisterEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RegisterEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly RegisterEndpoint _sut;
|
||||
private readonly RegisterRequestFixture _registerRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RegisterEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public RegisterEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<RegisterEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRegistrationTypeIsAdmin_ShouldSetupApplicationViaApi()
|
||||
{
|
||||
// Arrange
|
||||
RegisterRequest request = _registerRequestFixture.Create(registrationType: "Admin");
|
||||
_mockApiHttpClient.PostAsync<RegisterResponse, RegisterRequest>(Arg.Any<string>(), Arg.Any<RegisterRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new RegisterResponse(request.Username, null));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostAsync<RegisterResponse, RegisterRequest>(
|
||||
ApiRoutes.Initialization.SETUP_APPLICATION,
|
||||
Arg.Is<RegisterRequest>(registration => registration.Username == request.Username),
|
||||
Arg.Any<CancellationToken>());
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRegistrationTypeIsUser_ShouldRegisterAccountViaApi()
|
||||
{
|
||||
// Arrange
|
||||
RegisterRequest request = _registerRequestFixture.Create(registrationType: "User");
|
||||
_mockApiHttpClient.PostAsync<RegisterResponse, RegisterRequest>(Arg.Any<string>(), Arg.Any<RegisterRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new RegisterResponse(request.Username, null));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostAsync<RegisterResponse, RegisterRequest>(
|
||||
ApiRoutes.Authentication.REGISTER_ACCOUNT,
|
||||
Arg.Is<RegisterRequest>(registration => registration.Username == request.Username),
|
||||
Arg.Any<CancellationToken>());
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
}
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>disable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
|
||||
<IsPackable>false</IsPackable>
|
||||
<IsTestProject>true</IsTestProject>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<AssemblyAttribute Include="Xunit.CollectionBehaviorAttribute">
|
||||
<_Parameter1>DisableTestParallelization = true</_Parameter1>
|
||||
<_Parameter1_IsLiteral>true</_Parameter1_IsLiteral>
|
||||
</AssemblyAttribute>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AutoFixture.AutoNSubstitute" Version="5.0.0-preview0011" />
|
||||
<PackageReference Include="AutoFixture.Xunit2" Version="5.0.0-preview0011" />
|
||||
<PackageReference Include="Bogus" Version="35.6.5" />
|
||||
<PackageReference Include="coverlet.collector" Version="10.0.1">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="10.0.11" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.9.0" />
|
||||
<PackageReference Include="NSubstitute" Version="6.2.0" />
|
||||
<PackageReference Include="System.Linq.Async" Version="7.0.1" />
|
||||
<PackageReference Include="xunit" Version="2.9.3" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="4.0.0">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Using Include="Xunit" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\src\Lumina.Presentation.Web\Lumina.Presentation.Web.csproj" />
|
||||
<ProjectReference Include="..\..\Common\Lumina.Presentation.Web.Fixtures\Lumina.Presentation.Web.Fixtures.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
Reference in new issue
Block a user