mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 18:21:10 +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
@@ -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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user