mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 10:11: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,177 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Common.DTO.Configuration;
|
||||
using Lumina.Presentation.Web.Common.DTO.FileSystemManagement;
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Api;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Options;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Common.Api;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ApiHttpClient"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ApiHttpClientTests
|
||||
{
|
||||
private const string TEST_ENCRYPTION_KEY = "FLYO0QRo6u2VzoFOgNkkEwYNGtqhJ3QGZd7iAHNEJeM=";
|
||||
|
||||
[Fact]
|
||||
public async Task GetAsync_WhenApiReturnsSuccess_ShouldDeserializeResponseContent()
|
||||
{
|
||||
// Arrange
|
||||
TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.OK, """[{"title":"Library One"}]"""));
|
||||
ApiHttpClient sut = CreateSut(messageHandler);
|
||||
|
||||
// Act
|
||||
Lumina.Presentation.Web.Common.DTO.Libraries.LibraryDto[] result = await sut.GetAsync<Lumina.Presentation.Web.Common.DTO.Libraries.LibraryDto[]>("libraries", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Single(result);
|
||||
Assert.Equal("Library One", result[0].Title);
|
||||
Assert.Equal(new Uri("http://localhost:5214/api/v1/libraries"), messageHandler.Requests[0].RequestUri);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAsync_WhenApiReturnsError_ShouldThrowApiExceptionWithProblemDetails()
|
||||
{
|
||||
// Arrange
|
||||
string problemDetailsJson = """
|
||||
{
|
||||
"type": "https://tools.ietf.org/html/rfc4918#section-11.2",
|
||||
"title": "General.Validation",
|
||||
"status": 422,
|
||||
"detail": "OneOrMoreValidationErrorsOccurred"
|
||||
}
|
||||
""";
|
||||
TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.UnprocessableEntity, problemDetailsJson));
|
||||
ApiHttpClient sut = CreateSut(messageHandler);
|
||||
|
||||
// Act
|
||||
ApiException exception = await Assert.ThrowsAsync<ApiException>(() => sut.GetAsync<object>("libraries", CancellationToken.None));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, exception.HttpStatusCode);
|
||||
Assert.NotNull(exception.ProblemDetails);
|
||||
Assert.Equal("General.Validation", exception.ProblemDetails!.Title);
|
||||
Assert.Equal(422, exception.ProblemDetails.Status);
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", exception.ProblemDetails.Detail);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAsync_WhenApiReturnsEmptyContent_ShouldReturnDefault()
|
||||
{
|
||||
// Arrange
|
||||
TestApiHttpMessageHandler messageHandler = new(_ => new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(string.Empty) });
|
||||
ApiHttpClient sut = CreateSut(messageHandler);
|
||||
|
||||
// Act
|
||||
object? result = await sut.GetAsync<object>("libraries", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAsync_WhenUserHasTokenClaim_ShouldSendAuthorizationHeader()
|
||||
{
|
||||
// Arrange
|
||||
TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.OK, "{}"));
|
||||
ApiHttpClient sut = CreateSut(messageHandler, token: "test-jwt-token");
|
||||
|
||||
// Act
|
||||
await sut.GetAsync<object>("libraries", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("Bearer", messageHandler.Requests[0].Headers.Authorization!.Scheme);
|
||||
Assert.Equal("test-jwt-token", messageHandler.Requests[0].Headers.Authorization!.Parameter);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PostAsync_WhenCalled_ShouldSerializePayloadAndDeserializeResponse()
|
||||
{
|
||||
// Arrange
|
||||
TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.OK, """{"success":true}"""));
|
||||
ApiHttpClient sut = CreateSut(messageHandler);
|
||||
|
||||
// Act
|
||||
SuccessResponse result = await sut.PostAsync<SuccessResponse, object>("auth/login", new { username = "testuser" }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.Success);
|
||||
Assert.Equal(HttpMethod.Post, messageHandler.Requests[0].Method);
|
||||
Assert.Equal("http://localhost:5214/api/v1/auth/login", messageHandler.Requests[0].RequestUri!.ToString());
|
||||
Assert.Contains("testuser", messageHandler.RequestBodies[0]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteAsync_WhenApiReturnsError_ShouldThrowApiException()
|
||||
{
|
||||
// Arrange
|
||||
TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.InternalServerError, """{"title":"General.Failure","status":500}"""));
|
||||
ApiHttpClient sut = CreateSut(messageHandler);
|
||||
|
||||
// Act
|
||||
ApiException exception = await Assert.ThrowsAsync<ApiException>(() => sut.DeleteAsync("libraries/1", CancellationToken.None));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.InternalServerError, exception.HttpStatusCode);
|
||||
Assert.Equal("/api/v1/libraries/1", exception.RequestPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetBlobAsync_WhenApiReturnsSuccess_ShouldReturnBlobData()
|
||||
{
|
||||
// Arrange
|
||||
byte[] imageBytes = Encoding.UTF8.GetBytes("fake-image-bytes");
|
||||
TestApiHttpMessageHandler messageHandler = new(_ =>
|
||||
{
|
||||
HttpResponseMessage response = new(HttpStatusCode.OK) { Content = new ByteArrayContent(imageBytes) };
|
||||
response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/png");
|
||||
return response;
|
||||
});
|
||||
ApiHttpClient sut = CreateSut(messageHandler);
|
||||
|
||||
// Act
|
||||
BlobDataDto blob = await sut.GetBlobAsync("libraries/1/cover", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(imageBytes, blob.Data);
|
||||
Assert.Equal("image/png", blob.ContentType);
|
||||
}
|
||||
|
||||
private static ApiHttpClient CreateSut(TestApiHttpMessageHandler messageHandler, string? token = null)
|
||||
{
|
||||
HttpClient httpClient = new(messageHandler);
|
||||
IHttpContextAccessor httpContextAccessor = Substitute.For<IHttpContextAccessor>();
|
||||
if (token is not null)
|
||||
{
|
||||
DefaultHttpContext httpContext = new();
|
||||
httpContext.User = new ClaimsPrincipal(new ClaimsIdentity([new Claim("Token", token)], "TestAuthentication"));
|
||||
httpContextAccessor.HttpContext.Returns(httpContext);
|
||||
}
|
||||
IOptionsSnapshot<ServerConfigurationDto> serverConfigurationOptions = Substitute.For<IOptionsSnapshot<ServerConfigurationDto>>();
|
||||
serverConfigurationOptions.Value.Returns(new ServerConfigurationDto { ApiVersion = '1', BaseAddress = "http://localhost", Port = 5214 });
|
||||
return new ApiHttpClient(httpClient, httpContextAccessor, serverConfigurationOptions);
|
||||
}
|
||||
|
||||
private static HttpResponseMessage CreateJsonResponse(HttpStatusCode statusCode, string json)
|
||||
{
|
||||
return new HttpResponseMessage(statusCode)
|
||||
{
|
||||
Content = new StringContent(json, Encoding.UTF8, "application/json")
|
||||
};
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Authorization;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Common.Authorization;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="AuthorizationPolicies"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AuthorizationPoliciesTests
|
||||
{
|
||||
[Fact]
|
||||
public void PolicyNames_WhenRead_ShouldMatchExpectedPolicyNames()
|
||||
{
|
||||
// Act & Assert
|
||||
Assert.Equal("RequireAdminRole", AuthorizationPolicies.REQUIRE_ADMIN_ROLE);
|
||||
Assert.Equal("RequireCreateLibrariesPermission", AuthorizationPolicies.REQUIRE_CREATE_LIBRARIES_PERMISSION);
|
||||
Assert.Equal("RequireInitialization", AuthorizationPolicies.REQUIRE_INITIALIZATION);
|
||||
}
|
||||
}
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.Authorization;
|
||||
using Lumina.Presentation.Web.Common.Enums.Authorization;
|
||||
using Lumina.Presentation.Web.Common.Responses.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Security.Claims;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Common.Authorization;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="AuthorizationService"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AuthorizationServiceTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly AuthorizationService _sut;
|
||||
private readonly Guid _userId;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AuthorizationServiceTests"/> class.
|
||||
/// </summary>
|
||||
public AuthorizationServiceTests()
|
||||
{
|
||||
_userId = Guid.NewGuid();
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
IHttpContextAccessor httpContextAccessor = Substitute.For<IHttpContextAccessor>();
|
||||
DefaultHttpContext httpContext = new();
|
||||
httpContext.User = new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, _userId.ToString())], "TestAuthentication"));
|
||||
httpContextAccessor.HttpContext.Returns(httpContext);
|
||||
_sut = new AuthorizationService(_mockApiHttpClient, httpContextAccessor);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HasPermissionAsync_WhenUserHasPermission_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
_mockApiHttpClient.GetAsync<GetAuthorizationResponse>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new GetAuthorizationResponse(_userId, "Admin", [AuthorizationPermission.CanCreateLibraries]));
|
||||
|
||||
// Act
|
||||
bool result = await _sut.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HasPermissionAsync_WhenUserDoesNotHavePermission_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
_mockApiHttpClient.GetAsync<GetAuthorizationResponse>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new GetAuthorizationResponse(_userId, "Admin", [AuthorizationPermission.CanViewUsers]));
|
||||
|
||||
// Act
|
||||
bool result = await _sut.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task IsInRoleAsync_WhenRoleMatches_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
_mockApiHttpClient.GetAsync<GetAuthorizationResponse>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new GetAuthorizationResponse(_userId, "Admin", []));
|
||||
|
||||
// Act
|
||||
bool result = await _sut.IsInRoleAsync("Admin", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task IsInRoleAsync_WhenRoleDoesNotMatch_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
_mockApiHttpClient.GetAsync<GetAuthorizationResponse>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new GetAuthorizationResponse(_userId, "User", []));
|
||||
|
||||
// Act
|
||||
bool result = await _sut.IsInRoleAsync("Admin", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HasPermissionAsync_WhenCalled_ShouldRequestAuthorizationForCurrentUser()
|
||||
{
|
||||
// Arrange
|
||||
_mockApiHttpClient.GetAsync<GetAuthorizationResponse>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new GetAuthorizationResponse(_userId, "Admin", []));
|
||||
|
||||
// Act
|
||||
await _sut.HasPermissionAsync(AuthorizationPermission.CanViewUsers, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<GetAuthorizationResponse>(
|
||||
Arg.Is<string>(endpoint => endpoint.StartsWith($"auth/get-authorization?userId={_userId}", StringComparison.OrdinalIgnoreCase)),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Localization;
|
||||
using Microsoft.AspNetCore.Mvc.Localization;
|
||||
using Microsoft.Extensions.Localization;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Common.Localization;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="CoreHtmlLocalizerFactory"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class CoreHtmlLocalizerFactoryTests
|
||||
{
|
||||
private readonly IStringLocalizerFactory _mockStringLocalizerFactory;
|
||||
private readonly CoreHtmlLocalizerFactory _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CoreHtmlLocalizerFactoryTests"/> class.
|
||||
/// </summary>
|
||||
public CoreHtmlLocalizerFactoryTests()
|
||||
{
|
||||
_mockStringLocalizerFactory = Substitute.For<IStringLocalizerFactory>();
|
||||
_mockStringLocalizerFactory.Create(Arg.Any<string>(), Arg.Any<string>()).Returns(Substitute.For<IStringLocalizer>());
|
||||
_sut = new CoreHtmlLocalizerFactory(_mockStringLocalizerFactory);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenBaseNameStartsWithLocationCorePrefix_ShouldStripCoreSegment()
|
||||
{
|
||||
// Act
|
||||
IHtmlLocalizer localizer = _sut.Create("Lumina.Presentation.Web.Core.Views.Auth.Login", "Lumina.Presentation.Web");
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(localizer);
|
||||
_mockStringLocalizerFactory.Received(1).Create("Lumina.Presentation.Web.Views.Auth.Login", "Lumina.Presentation.Web");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenBaseNameDoesNotStartWithLocationCorePrefix_ShouldKeepBaseNameUnchanged()
|
||||
{
|
||||
// Act
|
||||
IHtmlLocalizer localizer = _sut.Create("Lumina.Presentation.Web.Views.Shared.Layout", "Lumina.Presentation.Web");
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(localizer);
|
||||
_mockStringLocalizerFactory.Received(1).Create("Lumina.Presentation.Web.Views.Shared.Layout", "Lumina.Presentation.Web");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenResourceSourceTypeProvided_ShouldCreateLocalizerForType()
|
||||
{
|
||||
// Arrange
|
||||
_mockStringLocalizerFactory.Create(Arg.Any<Type>()).Returns(Substitute.For<IStringLocalizer>());
|
||||
|
||||
// Act
|
||||
IHtmlLocalizer localizer = _sut.Create(typeof(TestLocalizationResource));
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(localizer);
|
||||
_mockStringLocalizerFactory.Received(1).Create(typeof(TestLocalizationResource));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Marker type used for the resource source based localizer creation test.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
private sealed class TestLocalizationResource
|
||||
{
|
||||
}
|
||||
}
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Configuration;
|
||||
using Lumina.Presentation.Web.Common.Security;
|
||||
using Microsoft.Extensions.Options;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Common.Security;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="CryptographyService"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class CryptographyServiceTests
|
||||
{
|
||||
private const string TEST_ENCRYPTION_KEY = "FLYO0QRo6u2VzoFOgNkkEwYNGtqhJ3QGZd7iAHNEJeM=";
|
||||
private readonly CryptographyService _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CryptographyServiceTests"/> class.
|
||||
/// </summary>
|
||||
public CryptographyServiceTests()
|
||||
{
|
||||
EncryptionSettingsDto settings = new() { SecretKey = TEST_ENCRYPTION_KEY };
|
||||
_sut = new CryptographyService(Options.Create(settings));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Encrypt_WhenCalled_ShouldReturnCiphertextThatDecryptsToPlaintext()
|
||||
{
|
||||
// Arrange
|
||||
const string plaintext = "sensitive-data";
|
||||
|
||||
// Act
|
||||
string ciphertext = _sut.Encrypt(plaintext);
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(plaintext, ciphertext);
|
||||
Assert.Equal(plaintext, _sut.Decrypt(ciphertext));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Encrypt_WhenCalledTwice_ShouldReturnDifferentCiphertexts()
|
||||
{
|
||||
// Arrange
|
||||
const string plaintext = "sensitive-data";
|
||||
|
||||
// Act
|
||||
string firstCiphertext = _sut.Encrypt(plaintext);
|
||||
string secondCiphertext = _sut.Encrypt(plaintext);
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(firstCiphertext, secondCiphertext);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)]
|
||||
[InlineData("")]
|
||||
public void Encrypt_WhenPlaintextIsNullOrEmpty_ShouldThrowArgumentException(string? plaintext)
|
||||
{
|
||||
// Act
|
||||
ArgumentException exception = Assert.Throws<ArgumentException>(() => _sut.Encrypt(plaintext!));
|
||||
|
||||
// Assert
|
||||
Assert.Equal("plaintext", exception.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Decrypt_WhenCiphertextIsNotValidBase64_ShouldThrowFormatException()
|
||||
{
|
||||
// Act
|
||||
FormatException exception = Assert.Throws<FormatException>(() => _sut.Decrypt("not-valid-base64!!!"));
|
||||
|
||||
// Assert
|
||||
Assert.Contains("Base-64", exception.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Decrypt_WhenCiphertextIsTooShort_ShouldThrowArgumentException()
|
||||
{
|
||||
// Act
|
||||
ArgumentException exception = Assert.Throws<ArgumentException>(() => _sut.Decrypt(Convert.ToBase64String([1, 2, 3])));
|
||||
|
||||
// Assert
|
||||
Assert.Equal("Invalid ciphertext", exception.Message);
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Services;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Common.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ScriptIdentifierHelper"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ScriptIdentifierHelperTests
|
||||
{
|
||||
[Fact]
|
||||
public void GenerateScriptId_WhenCalled_ShouldReturnScriptPrefixedIdentifier()
|
||||
{
|
||||
// Act
|
||||
string scriptId = ScriptIdentifierHelper.GenerateScriptId();
|
||||
|
||||
// Assert
|
||||
Assert.StartsWith("script_", scriptId);
|
||||
Assert.True(Guid.TryParse(scriptId.AsSpan("script_".Length), out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GenerateScriptId_WhenCalledTwice_ShouldReturnDistinctIdentifiers()
|
||||
{
|
||||
// Act
|
||||
string firstScriptId = ScriptIdentifierHelper.GenerateScriptId();
|
||||
string secondScriptId = ScriptIdentifierHelper.GenerateScriptId();
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(firstScriptId, secondScriptId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ClearIdentifier_WhenCalledWithGeneratedIdentifier_ShouldNotThrow()
|
||||
{
|
||||
// Arrange
|
||||
string scriptId = ScriptIdentifierHelper.GenerateScriptId();
|
||||
|
||||
// Act
|
||||
ScriptIdentifierHelper.ClearIdentifier(scriptId);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(scriptId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Common.Services;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Common.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="UrlService"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UrlServiceTests
|
||||
{
|
||||
private readonly IHttpContextAccessor _mockHttpContextAccessor;
|
||||
private readonly UrlService _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UrlServiceTests"/> class.
|
||||
/// </summary>
|
||||
public UrlServiceTests()
|
||||
{
|
||||
_mockHttpContextAccessor = Substitute.For<IHttpContextAccessor>();
|
||||
_sut = new UrlService(_mockHttpContextAccessor);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetAbsoluteUrl_WhenRouteTemplateIsNotDefined_ShouldThrowArgumentException()
|
||||
{
|
||||
// Act
|
||||
ArgumentException exception = Assert.Throws<ArgumentException>(() => _sut.GetAbsoluteUrl("/not-a-real-route"));
|
||||
|
||||
// Assert
|
||||
Assert.Contains("not defined in the WebRoutes constants", exception.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetAbsoluteUrl_WhenHttpContextIsNull_ShouldReturnNull()
|
||||
{
|
||||
// Arrange
|
||||
_mockHttpContextAccessor.HttpContext.Returns((HttpContext?)null);
|
||||
|
||||
// Act
|
||||
string? url = _sut.GetAbsoluteUrl(WebRoutes.Authentication.LOGIN);
|
||||
|
||||
// Assert
|
||||
Assert.Null(url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetAbsoluteUrl_WhenCalled_ShouldReplaceCulturePlaceholderAndBuildAbsoluteUrl()
|
||||
{
|
||||
// Arrange
|
||||
DefaultHttpContext httpContext = CreateHttpContext(culture: "en-us", pathBase: "", host: "localhost:5012", scheme: "http");
|
||||
_mockHttpContextAccessor.HttpContext.Returns(httpContext);
|
||||
|
||||
// Act
|
||||
string? url = _sut.GetAbsoluteUrl(WebRoutes.Authentication.LOGIN);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("http://localhost:5012/en-us/auth/api-login", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetAbsoluteUrl_WhenCalledWithAdditionalRouteValues_ShouldReplacePlaceholders()
|
||||
{
|
||||
// Arrange
|
||||
DefaultHttpContext httpContext = CreateHttpContext(culture: "en-us", pathBase: "", host: "localhost:5012", scheme: "http");
|
||||
_mockHttpContextAccessor.HttpContext.Returns(httpContext);
|
||||
Guid id = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
string? url = _sut.GetAbsoluteUrl(WebRoutes.LibraryManagement.DELETE_LIBRARY, new { id });
|
||||
|
||||
// Assert
|
||||
Assert.Equal($"http://localhost:5012/en-us/libraries/manage/api-item/{id}", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetAbsoluteUrl_WhenPathBaseIsPresent_ShouldIncludePathBase()
|
||||
{
|
||||
// Arrange
|
||||
DefaultHttpContext httpContext = CreateHttpContext(culture: "de-de", pathBase: "/lumina", host: "localhost:5012", scheme: "https");
|
||||
_mockHttpContextAccessor.HttpContext.Returns(httpContext);
|
||||
|
||||
// Act
|
||||
string? url = _sut.GetAbsoluteUrl(WebRoutes.Authentication.REGISTER_VIEW);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("https://localhost:5012/lumina/de-de/auth/register", url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetAbsoluteUrl_WhenRouteTemplateDoesNotStartWithSlash_ShouldPrependSlash()
|
||||
{
|
||||
// Arrange
|
||||
DefaultHttpContext httpContext = CreateHttpContext(culture: "en-us", pathBase: "", host: "localhost:5012", scheme: "http");
|
||||
_mockHttpContextAccessor.HttpContext.Returns(httpContext);
|
||||
|
||||
// Act
|
||||
string? url = _sut.GetAbsoluteUrl(WebRoutes.FileSystem.GET_TYPE);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("http://localhost:5012/file-system/api-get-type", url);
|
||||
}
|
||||
|
||||
private static DefaultHttpContext CreateHttpContext(string culture, string pathBase, string host, string scheme)
|
||||
{
|
||||
DefaultHttpContext httpContext = new();
|
||||
httpContext.Request.RouteValues["culture"] = culture;
|
||||
httpContext.Request.PathBase = pathBase;
|
||||
httpContext.Request.Host = new HostString(host);
|
||||
httpContext.Request.Scheme = scheme;
|
||||
return httpContext;
|
||||
}
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentValidation;
|
||||
using FluentValidation.Results;
|
||||
using Lumina.Presentation.Web.Common.DTO.Configuration;
|
||||
using Lumina.Presentation.Web.Common.Validators;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Common.Validators;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="EncryptionSettingsModelValidator"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class EncryptionSettingsModelValidatorTests
|
||||
{
|
||||
private const string VALID_BASE64_KEY = "FLYO0QRo6u2VzoFOgNkkEwYNGtqhJ3QGZd7iAHNEJeM=";
|
||||
private readonly EncryptionSettingsModelValidator _validator = new();
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenSecretKeyIsEmpty_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
EncryptionSettingsDto settings = new() { SecretKey = string.Empty };
|
||||
|
||||
// Act
|
||||
ValidationResult result = _validator.Validate(settings);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsValid);
|
||||
Assert.Contains(result.Errors, error => error.PropertyName == nameof(EncryptionSettingsDto.SecretKey) && error.ErrorMessage == "Encryption secret key cannot be empty!");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenSecretKeyIsNotBase64_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
EncryptionSettingsDto settings = new() { SecretKey = "not-base64-key!" };
|
||||
|
||||
// Act
|
||||
ValidationResult result = _validator.Validate(settings);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsValid);
|
||||
Assert.Contains(result.Errors, error => error.PropertyName == nameof(EncryptionSettingsDto.SecretKey) && error.ErrorMessage == "Encryption secret key must be a base64 string!");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenSecretKeyIsValidBase64_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
EncryptionSettingsDto settings = new() { SecretKey = VALID_BASE64_KEY };
|
||||
|
||||
// Act
|
||||
ValidationResult result = _validator.Validate(settings);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsValid);
|
||||
}
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentValidation;
|
||||
using FluentValidation.Results;
|
||||
using Lumina.Presentation.Web.Common.DTO.Configuration;
|
||||
using Lumina.Presentation.Web.Common.Validators;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Common.Validators;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ServerConfigurationModelValidator"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ServerConfigurationModelValidatorTests
|
||||
{
|
||||
private readonly ServerConfigurationModelValidator _validator = new();
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenBaseAddressIsEmpty_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
ServerConfigurationDto configuration = new() { ApiVersion = '1', BaseAddress = string.Empty, Port = 5214 };
|
||||
|
||||
// Act
|
||||
ValidationResult result = _validator.Validate(configuration);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsValid);
|
||||
Assert.Contains(result.Errors, error => error.PropertyName == nameof(ServerConfigurationDto.BaseAddress) && error.ErrorMessage == "Base address cannot be empty!");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData((ushort)0)] // minimum allowed value
|
||||
[InlineData((ushort)65535)] // maximum allowed value
|
||||
public void Validate_WhenPortIsAtBoundary_ShouldNotHaveValidationError(ushort port)
|
||||
{
|
||||
// Arrange
|
||||
ServerConfigurationDto configuration = new() { ApiVersion = '1', BaseAddress = "http://localhost", Port = port };
|
||||
|
||||
// Act
|
||||
ValidationResult result = _validator.Validate(configuration);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsValid);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData((char)0)] // minimum allowed API version
|
||||
[InlineData((char)255)] // maximum allowed API version
|
||||
public void Validate_WhenApiVersionIsAtBoundary_ShouldNotHaveValidationError(char apiVersion)
|
||||
{
|
||||
// Arrange
|
||||
ServerConfigurationDto configuration = new() { ApiVersion = apiVersion, BaseAddress = "http://localhost", Port = 5214 };
|
||||
|
||||
// Act
|
||||
ValidationResult result = _validator.Validate(configuration);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsValid);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenConfigurationIsValid_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
ServerConfigurationDto configuration = new() { ApiVersion = '1', BaseAddress = "http://localhost", Port = 5214 };
|
||||
|
||||
// Act
|
||||
ValidationResult result = _validator.Validate(configuration);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsValid);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user