Heimdall Gitea / Build and tests (pull_request) Failing after 8m51s
Heimdall Gitea / Build and scan server image (pull_request) Skipped
Heimdall Gitea / Build and scan agent image (pull_request) Skipped
Heimdall Gitea / Publish Docker Hub latest tags (pull_request) Skipped
Heimdall Gitea / Publish versioned release (pull_request) Skipped
167 lines
6.9 KiB
C#
167 lines
6.9 KiB
C#
using System.Net;
|
|
using System.Net.Http.Json;
|
|
using System.Text.Json;
|
|
using Bunit;
|
|
using Heimdall.Web.Services;
|
|
using Microsoft.AspNetCore.Components;
|
|
using Microsoft.AspNetCore.Components.Authorization;
|
|
using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage;
|
|
using Microsoft.AspNetCore.DataProtection;
|
|
using Microsoft.AspNetCore.Hosting;
|
|
using Microsoft.AspNetCore.Http;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.Extensions.Logging;
|
|
using Microsoft.JSInterop;
|
|
using NSubstitute;
|
|
|
|
namespace Heimdall.Web.Tests.Components.Pages;
|
|
|
|
/// <summary>
|
|
/// Base class for Blazor page tests (Heimdall.Web.Components.Pages).
|
|
///
|
|
/// HeimdallApiClient has no virtual members, so NSubstitute cannot substitute
|
|
/// it directly. Following the existing project pattern (see
|
|
/// HeimdallApiClientTests), we register the REAL HeimdallApiClient backed by a
|
|
/// routed in-memory HttpMessageHandler — the API is never hit for real.
|
|
/// </summary>
|
|
public abstract class PageTestBase : MudTestBase
|
|
{
|
|
/// <summary>In-memory HTTP handler that routes responses by HTTP method + path.</summary>
|
|
protected RoutedHandler Handler { get; } = new();
|
|
|
|
/// <summary>Shared AuthState instance (also used by the Api client).</summary>
|
|
protected AuthState AuthState { get; } = new();
|
|
|
|
/// <summary>The real HeimdallApiClient wired to <see cref="Handler"/>.</summary>
|
|
protected HeimdallApiClient Api { get; }
|
|
|
|
/// <summary>Substituted HeimdallAuthStateProvider (Login/Register/Profile inject it).</summary>
|
|
protected HeimdallAuthStateProvider AuthProvider { get; }
|
|
|
|
/// <summary>Development environment stub (Error page shows dev hints).</summary>
|
|
protected IWebHostEnvironment Environment { get; } = Substitute.For<IWebHostEnvironment>();
|
|
|
|
protected PageTestBase()
|
|
{
|
|
// Longer default wait timeout: bUnit defaults to 1s, which is too
|
|
// short on the CI runner (flaky WaitForAssertion). 10s keeps local
|
|
// runs fast and CI green.
|
|
DefaultWaitTimeout = TimeSpan.FromSeconds(10);
|
|
|
|
// ILogger<T> (required by Login page) — silent by default
|
|
Services.AddLogging();
|
|
Services.AddScoped<UiLanguageService>();
|
|
Services.AddScoped<UiText>();
|
|
|
|
var httpClient = new HttpClient(Handler) { BaseAddress = new Uri("http://localhost/") };
|
|
var httpFactory = Substitute.For<IHttpClientFactory>();
|
|
httpFactory.CreateClient("HeimdallApi").Returns(httpClient);
|
|
|
|
Api = new HeimdallApiClient(httpFactory, AuthState);
|
|
AuthProvider = CreateAuthStateProvider();
|
|
|
|
Services.AddScoped(_ => AuthState);
|
|
Services.AddScoped(_ => Api);
|
|
Services.AddScoped(_ => AuthProvider);
|
|
Services.AddScoped(_ => Environment);
|
|
Services.AddScoped(sp => new NotificationsHubClient(
|
|
AuthState,
|
|
Services.GetRequiredService<NavigationManager>(),
|
|
Substitute.For<Microsoft.Extensions.Logging.ILogger<NotificationsHubClient>>()));
|
|
}
|
|
|
|
/// <summary>Logs the shared AuthState in as the given role.</summary>
|
|
protected void LoginAs(string role = "Admin", string displayName = "Admin User")
|
|
{
|
|
AuthState.Login(new AuthResponse(
|
|
"access-token", "refresh-token", DateTime.UtcNow.AddHours(1), false,
|
|
new UserInfo(Guid.NewGuid(), "admin@heimdall.local", displayName, [role])));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Renders a page inside HostWithProviders so MudPopoverProvider and
|
|
/// MudDialogProvider are present — required for pages with inline
|
|
/// MudDialog components (their content is rendered by the providers, so
|
|
/// it appears in the HOST markup, not the page markup). Returns the host;
|
|
/// find the page with host.FindComponent<T>() when needed.
|
|
/// </summary>
|
|
protected IRenderedComponent<HostWithProviders> RenderPage<T>(
|
|
Action<ComponentParameterCollectionBuilder<T>>? parameters = null)
|
|
where T : IComponent
|
|
{
|
|
return Render<HostWithProviders>(p => p.AddChildContent<T>(parameters ?? (_ => { })));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Creates a NSubstitute-backed HeimdallAuthStateProvider (constructor args
|
|
/// are stubbed). Used by Login/Register/Profile pages.
|
|
/// </summary>
|
|
protected HeimdallAuthStateProvider CreateAuthStateProvider()
|
|
{
|
|
var provider = Substitute.For<HeimdallAuthStateProvider>(
|
|
new ProtectedSessionStorage(
|
|
Substitute.For<IJSRuntime>(),
|
|
Substitute.For<IDataProtectionProvider>()),
|
|
AuthState,
|
|
Substitute.For<IHttpContextAccessor>());
|
|
|
|
provider.GetAuthenticationStateAsync().Returns(Task.FromResult(
|
|
new AuthenticationState(new System.Security.Claims.ClaimsPrincipal(
|
|
new System.Security.Claims.ClaimsIdentity("test")))));
|
|
return provider;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// In-memory HttpMessageHandler that dispatches requests to registered
|
|
/// responders based on HTTP method and path substrings. Robust against
|
|
/// parallel calls (unlike a FIFO queue).
|
|
/// </summary>
|
|
public sealed class RoutedHandler : HttpMessageHandler
|
|
{
|
|
private readonly List<(HttpMethod Method, string PathContains, Func<HttpResponseMessage> Responder)> _routes = [];
|
|
|
|
/// <summary>All requests received, for assertions.</summary>
|
|
public List<HttpRequestMessage> Requests { get; } = [];
|
|
|
|
public void On(HttpMethod method, string pathContains, Func<HttpResponseMessage> responder)
|
|
=> _routes.Add((method, pathContains, responder));
|
|
|
|
public void On(HttpMethod method, string pathContains, object body)
|
|
=> On(method, pathContains, () => JsonResponse(HttpStatusCode.OK, body));
|
|
|
|
public void On(HttpMethod method, string pathContains, HttpStatusCode status)
|
|
=> On(method, pathContains, () => new HttpResponseMessage(status));
|
|
|
|
/// <summary>Convenience for GET routes returning a JSON body.</summary>
|
|
public void OnGet(string pathContains, object body) => On(HttpMethod.Get, pathContains, body);
|
|
public void OnGet(string pathContains, HttpStatusCode status) => On(HttpMethod.Get, pathContains, status);
|
|
|
|
public static HttpResponseMessage JsonResponse(HttpStatusCode status, object body) => new(status)
|
|
{
|
|
Content = JsonContent.Create(body, options: new JsonSerializerOptions
|
|
{
|
|
PropertyNameCaseInsensitive = true,
|
|
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
|
|
})
|
|
};
|
|
|
|
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken ct)
|
|
{
|
|
Requests.Add(request);
|
|
var path = request.RequestUri?.AbsolutePath ?? "";
|
|
|
|
HttpResponseMessage response = new(HttpStatusCode.NotFound);
|
|
foreach (var (method, pathContains, responder) in _routes)
|
|
{
|
|
if (request.Method == method && path.Contains(pathContains, StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
response = responder();
|
|
break;
|
|
}
|
|
}
|
|
|
|
return Task.FromResult(response);
|
|
}
|
|
}
|