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,52 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.IntegrationTests.Common.Documentation;
/// <summary>
/// Contains integration tests for the OpenAPI and Scalar documentation endpoints of the Web application.
/// </summary>
[ExcludeFromCodeCoverage]
public class OpenApiEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly HttpClient _client;
/// <summary>
/// Initializes a new instance of the <see cref="OpenApiEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
public OpenApiEndpointTests(LuminaWebFactory apiFactory)
{
_client = apiFactory.CreateClient();
}
[Fact]
public async Task OpenApi_WhenRequested_ShouldServeDocument()
{
// Act
HttpResponseMessage response = await _client.GetAsync("/openapi/v1.json");
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.Contains("openapi", content);
}
[Fact]
public async Task Scalar_WhenRequested_ShouldServeReferencePage()
{
// Act
HttpResponseMessage response = await _client.GetAsync("/scalar/v1");
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType);
}
}
@@ -0,0 +1,63 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Fixtures.Common.Api;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Presentation.Web.IntegrationTests.Common.Setup;
/// <summary>
/// Factory for creating the Web application for integration tests, with the remote API client replaced by a configurable stub.
/// </summary>
[ExcludeFromCodeCoverage]
public class LuminaWebFactory : WebApplicationFactory<Program>, IDisposable
{
private const string TEST_ENCRYPTION_KEY = "FLYO0QRo6u2VzoFOgNkkEwYNGtqhJ3QGZd7iAHNEJeM=";
/// <summary>
/// Gets the stub used in place of the remote API client.
/// </summary>
public StubApiHttpClient ApiClientStub { get; } = new();
/// <summary>
/// Initializes a new instance of the <see cref="LuminaWebFactory"/> class.
/// </summary>
public LuminaWebFactory()
{
}
/// <summary>
/// Configures the web host for the integration tests.
/// </summary>
/// <param name="builder">The web host builder to configure.</param>
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.ConfigureAppConfiguration((context, config) =>
{
// provide the application configuration values that the Web app validates on startup
config.AddInMemoryCollection(initialData: new Dictionary<string, string?>
{
["EncryptionSettings:SecretKey"] = TEST_ENCRYPTION_KEY,
["ServerConfiguration:ApiVersion"] = "1",
["ServerConfiguration:BaseAddress"] = "http://localhost",
["ServerConfiguration:Port"] = "5214"
});
});
builder.ConfigureServices(services =>
{
// remove the typed HTTP client registration, so that the stub can take its place
ServiceDescriptor[] apiClientDescriptors = services.Where(serviceDescriptor => serviceDescriptor.ServiceType == typeof(IApiHttpClient)).ToArray();
foreach (ServiceDescriptor descriptor in apiClientDescriptors)
services.Remove(descriptor);
services.AddSingleton<IApiHttpClient>(ApiClientStub);
});
}
}
@@ -0,0 +1,70 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.DTO.Authorization;
using Lumina.Presentation.Web.Common.Responses.Authorization;
using Lumina.Presentation.Web.Core.Endpoints.Admin.Authorization.Roles.GetRoles;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Authorization.Roles.GetRoles;
/// <summary>
/// Contains integration tests for the <c>/{culture}/admin/api-get-roles</c> route served by the <see cref="GetRolesEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetRolesEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
/// <summary>
/// Initializes a new instance of the <see cref="GetRolesEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
public GetRolesEndpointTests(LuminaWebFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task GetRoles_WhenCalledByAdminUser_ShouldReturnRolesJson()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
_apiFactory.ApiClientStub.AuthorizationResponse = new GetAuthorizationResponse(Guid.NewGuid(), "Admin", []);
RoleDto[] expectedRoles = [new RoleDto(Guid.NewGuid(), "Admin"), new RoleDto(Guid.NewGuid(), "User")];
_apiFactory.ApiClientStub.RegisterGetResponse("auth/roles", expectedRoles);
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
// Act
HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/api-get-roles");
string content = await response.Content.ReadAsStringAsync();
// Assert
response.EnsureSuccessStatusCode();
using JsonDocument json = JsonDocument.Parse(content);
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
Assert.Equal(2, json.RootElement.GetProperty("data").GetArrayLength());
}
[Fact]
public async Task GetRoles_WhenCalledByNonAdminUser_ShouldRedirectToAccessDenied()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
_apiFactory.ApiClientStub.AuthorizationResponse = new GetAuthorizationResponse(Guid.NewGuid(), "User", []);
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
// Act
HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/api-get-roles");
// Assert
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Contains("access-denied", response.Headers.Location!.ToString());
}
}
@@ -0,0 +1,91 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Core.Endpoints.Home;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Home;
/// <summary>
/// Contains integration tests for the <c>/{culture}</c> and <c>/</c> routes served by the <see cref="HomeIndexEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class HomeIndexEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
/// <summary>
/// Initializes a new instance of the <see cref="HomeIndexEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
public HomeIndexEndpointTests(LuminaWebFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task Home_WhenCalledWithoutCulture_ShouldRedirectToDefaultCulture()
{
// Arrange
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
// Act
HttpResponseMessage response = await client.GetAsync("/");
// Assert
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Equal("/en-us/", response.Headers.Location!.ToString());
}
[Fact]
public async Task Home_WhenCalledWithoutAuthentication_ShouldRedirectToLogin()
{
// Arrange
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
// Act
HttpResponseMessage response = await client.GetAsync("/en-us");
// Assert
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
}
[Fact]
public async Task Home_WhenCalledByAuthenticatedUser_ShouldReturnHomePage()
{
// Arrange
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
// Act
HttpResponseMessage response = await webClient.Client.GetAsync("/en-us");
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType);
string content = await response.Content.ReadAsStringAsync();
Assert.Contains("html", content);
}
[Theory]
[InlineData("/de-de")] // German culture
[InlineData("/fr-fr")] // French culture
[InlineData("/ja-jp")] // Japanese culture
public async Task Home_WhenCalledByAuthenticatedUserWithLocalizedCulture_ShouldReturnHomePage(string culturePath)
{
// Arrange
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
// Act
HttpResponseMessage response = await webClient.Client.GetAsync(culturePath);
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
@@ -0,0 +1,90 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.DTO.Libraries;
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraries;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.GetLibraries;
/// <summary>
/// Contains integration tests for the <c>/{culture}/libraries/manage/api-get-libraries</c> route served by the <see cref="GetLibrariesEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibrariesEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
/// <summary>
/// Initializes a new instance of the <see cref="GetLibrariesEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
public GetLibrariesEndpointTests(LuminaWebFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task GetLibraries_WhenCalledByAuthenticatedUser_ShouldReturnLibrariesJson()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
LibraryDto[] expectedLibraries =
[
new LibraryDto { Id = Guid.NewGuid(), Title = "Books", LibraryType = "Book" },
new LibraryDto { Id = Guid.NewGuid(), Title = "Movies", LibraryType = "Video" }
];
_apiFactory.ApiClientStub.RegisterGetResponse("libraries", expectedLibraries);
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
// Act
HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/libraries/manage/api-get-libraries");
string content = await response.Content.ReadAsStringAsync();
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using JsonDocument json = JsonDocument.Parse(content);
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
JsonElement data = json.RootElement.GetProperty("data");
Assert.Equal(2, data.GetArrayLength());
Assert.Equal("Books", data[0].GetProperty("title").GetString());
}
[Fact]
public async Task GetLibraries_WhenCalledWithoutAuthentication_ShouldRedirectToLogin()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
// Act
HttpResponseMessage response = await client.GetAsync("/en-us/libraries/manage/api-get-libraries");
// Assert
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
}
[Fact]
public async Task GetLibraries_WhenCalled_ShouldRequestLibrariesFromApi()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
_apiFactory.ApiClientStub.RegisterGetResponse("libraries", Array.Empty<LibraryDto>());
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
// Act
HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/libraries/manage/api-get-libraries");
// Assert
response.EnsureSuccessStatusCode();
Assert.Contains("libraries", _apiFactory.ApiClientStub.GetEndpointsCalled);
}
}
@@ -0,0 +1,84 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.DTO.Libraries;
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.SaveLibrary;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.SaveLibrary;
/// <summary>
/// Contains integration tests for the <c>/{culture}/libraries/manage/api-item</c> route served by the <see cref="SaveLibraryEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SaveLibraryEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
/// <summary>
/// Initializes a new instance of the <see cref="SaveLibraryEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
public SaveLibraryEndpointTests(LuminaWebFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task SaveLibrary_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldSaveLibraryAndReturnSuccess()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
LibraryDto request = new() { Title = "New Books Library", LibraryType = "Book" };
LibraryDto expectedResponse = new() { Id = Guid.NewGuid(), Title = request.Title, LibraryType = request.LibraryType };
_apiFactory.ApiClientStub.RegisterPostResponse("libraries", expectedResponse);
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage saveRequest = new(HttpMethod.Post, "/en-us/libraries/manage/api-item")
{
Content = JsonContent.Create(request)
};
saveRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
saveRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest);
string content = await response.Content.ReadAsStringAsync();
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using JsonDocument json = JsonDocument.Parse(content);
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
Assert.Contains(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "libraries");
}
[Fact]
public async Task SaveLibrary_WhenCalledWithoutAntiforgeryToken_ShouldReturnBadRequest()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage saveRequest = new(HttpMethod.Post, "/en-us/libraries/manage/api-item")
{
Content = JsonContent.Create(new LibraryDto { Title = "New Books Library", LibraryType = "Book" })
};
saveRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
saveRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest);
// Assert
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "libraries");
}
}
@@ -0,0 +1,61 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Core.Endpoints.Tools.Language.SetLanguage;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Tools.Language.SetLanguage;
/// <summary>
/// Contains integration tests for the <c>/{culture}/tools/language/set-language</c> route served by the <see cref="SetLanguageEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetLanguageEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
/// <summary>
/// Initializes a new instance of the <see cref="SetLanguageEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
public SetLanguageEndpointTests(LuminaWebFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task SetLanguage_WhenCalledByAuthenticatedUser_ShouldSetCultureCookieAndRedirectWithNewCulture()
{
// Arrange
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
string returnUrl = Uri.EscapeDataString("/en-us/tools/settings");
// Act
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/tools/language/set-language?newCulture=de-DE&returnUrl={returnUrl}");
// Assert
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Equal("/de-de/tools/settings", response.Headers.Location!.ToString());
Assert.Contains("de-DE", response.Headers.GetValues("Set-Cookie").First());
}
[Fact]
public async Task SetLanguage_WhenCalledWithoutAuthentication_ShouldRedirectToLogin()
{
// Arrange
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
// Act
HttpResponseMessage response = await client.GetAsync("/en-us/tools/language/set-language?newCulture=de-DE");
// Assert
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
}
}
@@ -0,0 +1,138 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.DTO.Common;
using Lumina.Presentation.Web.Common.Exceptions;
using Lumina.Presentation.Web.Common.Requests.UsersManagement;
using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.Login;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.UsersManagement.Authentication.Login;
/// <summary>
/// Contains integration tests for the <c>/{culture}/auth/api-login</c> route served by the <see cref="LoginEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LoginEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
/// <summary>
/// Initializes a new instance of the <see cref="LoginEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
public LoginEndpointTests(LuminaWebFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task Login_WithValidCredentials_ShouldSignInAndReturnRedirectUrl()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client);
HttpRequestMessage loginRequest = CreateLoginRequest(new LoginRequest(Username: "testuser", Password: "TestPass123!"), antiforgeryToken);
// Act
HttpResponseMessage response = await client.SendAsync(loginRequest);
using JsonDocument json = await WebTestHelpers.ReadJsonAsync(response);
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
Assert.Equal("/en-us/", json.RootElement.GetProperty("data").GetString());
string allSetCookies = string.Join("; ", response.Headers.GetValues("Set-Cookie"));
Assert.Contains(".Lumina.Auth", allSetCookies);
Assert.Contains("Token=", allSetCookies);
}
[Fact]
public async Task Login_WhenTotpRequired_ShouldReturnTotpRequiredSignal()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
ProblemDetailsDto problemDetails = new()
{
Title = "General.Validation",
Detail = "OneOrMoreValidationErrorsOccurred",
Extensions = new Dictionary<string, JsonElement>
{
["errors"] = CreateErrorsElement(["InvalidTotpCode"])
}
};
_apiFactory.ApiClientStub.RegisterPostException("auth/login", new ApiException(problemDetails, HttpStatusCode.UnprocessableEntity, "auth/login"));
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client);
HttpRequestMessage loginRequest = CreateLoginRequest(new LoginRequest(Username: "testuser", Password: "TestPass123!"), antiforgeryToken);
// Act
HttpResponseMessage response = await client.SendAsync(loginRequest);
using JsonDocument json = await WebTestHelpers.ReadJsonAsync(response);
// Assert
response.EnsureSuccessStatusCode();
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
Assert.True(json.RootElement.GetProperty("data").GetProperty("isTotpRequired").GetBoolean());
}
[Fact]
public async Task Login_WhenApiReturnsForbidden_ShouldReturnFailureJson()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
_apiFactory.ApiClientStub.RegisterPostException("auth/login", new ApiException(new ProblemDetailsDto { Title = "General.Failure", Detail = "InvalidUsernameOrPassword" }, HttpStatusCode.Forbidden, "auth/login"));
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client);
HttpRequestMessage loginRequest = CreateLoginRequest(new LoginRequest(Username: "testuser", Password: "WrongPass123!"), antiforgeryToken);
// Act
HttpResponseMessage response = await client.SendAsync(loginRequest);
using JsonDocument json = await WebTestHelpers.ReadJsonAsync(response);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
Assert.Contains("<b>", json.RootElement.GetProperty("errorMessage").GetString());
}
private static HttpRequestMessage CreateLoginRequest(LoginRequest request, string antiforgeryToken)
{
HttpRequestMessage loginRequest = new(HttpMethod.Post, "/en-us/auth/api-login")
{
Content = JsonContent.Create(request)
};
loginRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
loginRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
loginRequest.Headers.Add("RequestVerificationToken", antiforgeryToken);
return loginRequest;
}
private static JsonElement CreateErrorsElement(string[] errorCodes)
{
using MemoryStream stream = new();
using (Utf8JsonWriter writer = new(stream))
{
writer.WriteStartObject();
writer.WriteStartArray("General.Validation");
foreach (string errorCode in errorCodes)
writer.WriteStringValue(errorCode);
writer.WriteEndArray();
writer.WriteEndObject();
}
return JsonDocument.Parse(stream.ToArray()).RootElement.Clone();
}
}
@@ -0,0 +1,79 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.Login;
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.UsersManagement.Authentication.Login;
/// <summary>
/// Contains integration tests for the <c>/{culture}/auth/login/{returnUrl?}</c> route served by the <see cref="LoginViewEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LoginViewEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
/// <summary>
/// Initializes a new instance of the <see cref="LoginViewEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
public LoginViewEndpointTests(LuminaWebFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task LoginView_WhenCalled_ShouldRenderLoginPage()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
// Act
HttpResponseMessage response = await client.GetAsync("/en-us/auth/login");
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType);
string content = await response.Content.ReadAsStringAsync();
Assert.Contains("login-form", content);
}
[Theory]
[InlineData("/de-de/auth/login")] // German culture
[InlineData("/fr-fr/auth/login")] // French culture
[InlineData("/zh-cn/auth/login")] // Chinese culture
public async Task LoginView_WhenCalledWithLocalizedCulture_ShouldRenderLoginPage(string culturePath)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
// Act
HttpResponseMessage response = await client.GetAsync(culturePath);
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.Contains("login-form", content);
}
[Fact]
public async Task LoginView_WhenCalledWithReturnUrl_ShouldPreserveReturnUrlInView()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
// Act
HttpResponseMessage response = await client.GetAsync("/en-us/auth/login/some-return-url");
// Assert
response.EnsureSuccessStatusCode();
string content = await response.Content.ReadAsStringAsync();
Assert.Contains("some-return-url", content);
}
}
@@ -0,0 +1,46 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>disable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<AssemblyAttribute Include="Xunit.CollectionBehaviorAttribute">
<_Parameter1>DisableTestParallelization = true</_Parameter1>
<_Parameter1_IsLiteral>true</_Parameter1_IsLiteral>
</AssemblyAttribute>
</ItemGroup>
<ItemGroup>
<PackageReference Include="AutoFixture.AutoNSubstitute" Version="5.0.0-preview0011" />
<PackageReference Include="AutoFixture.Xunit2" Version="5.0.0-preview0011" />
<PackageReference Include="Bogus" Version="35.6.5" />
<PackageReference Include="coverlet.collector" Version="10.0.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.11" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="10.0.11" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.9.0" />
<PackageReference Include="NSubstitute" Version="6.2.0" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="4.0.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\src\Lumina.Presentation.Web\Lumina.Presentation.Web.csproj" />
<ProjectReference Include="..\..\Common\Lumina.Presentation.Web.Fixtures\Lumina.Presentation.Web.Fixtures.csproj" />
</ItemGroup>
</Project>