test: adds unit, integration and security test projects for the web project

This commit is contained in:
BinaryAlley committed 2026-08-17 11:52:28 -07:00
1 parent 7b56033a15
commit 7ad7ad308e
70 files changed
+4993

No files matched your search

@@ -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")
};
}
}
@@ -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);
}
}
@@ -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>());
}
}
@@ -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
{
}
}
@@ -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);
}
}
@@ -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;
}
}
@@ -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);
}
}
@@ -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);
}
}
@@ -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());
}
}
@@ -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());
}
}
@@ -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>());
}
}
@@ -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);
}
}
@@ -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>());
}
}
@@ -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());
}
}
@@ -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());
}
}
@@ -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>());
}
}
@@ -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());
}
}
@@ -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());
}
}
@@ -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>());
}
}
@@ -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>());
}
}
@@ -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());
}
}
@@ -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);
}
}
@@ -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>());
}
}
@@ -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());
}
}
@@ -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);
}
}
@@ -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());
}
}
@@ -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());
}
}
@@ -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>