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