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.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.JSInterop;
using NSubstitute;
namespace Heimdall.Web.Tests.Components.Pages;
///
/// 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.
///
public abstract class PageTestBase : MudTestBase
{
/// In-memory HTTP handler that routes responses by HTTP method + path.
protected RoutedHandler Handler { get; } = new();
/// Shared AuthState instance (also used by the Api client).
protected AuthState AuthState { get; } = new();
/// The real HeimdallApiClient wired to .
protected HeimdallApiClient Api { get; }
/// Substituted HeimdallAuthStateProvider (Login/Register/Profile inject it).
protected HeimdallAuthStateProvider AuthProvider { get; }
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 (required by Login page) — silent by default
Services.AddLogging();
var httpClient = new HttpClient(Handler) { BaseAddress = new Uri("http://localhost/") };
var httpFactory = Substitute.For();
httpFactory.CreateClient("HeimdallApi").Returns(httpClient);
Api = new HeimdallApiClient(httpFactory, AuthState);
AuthProvider = CreateAuthStateProvider();
Services.AddScoped(_ => AuthState);
Services.AddScoped(_ => Api);
Services.AddScoped(_ => AuthProvider);
}
/// Logs the shared AuthState in as the given role.
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])));
}
///
/// 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.
///
protected IRenderedComponent RenderPage(
Action>? parameters = null)
where T : IComponent
{
return Render(p => p.AddChildContent(parameters ?? (_ => { })));
}
///
/// Creates a NSubstitute-backed HeimdallAuthStateProvider (constructor args
/// are stubbed). Used by Login/Register/Profile pages.
///
protected HeimdallAuthStateProvider CreateAuthStateProvider()
{
var provider = Substitute.For(
new ProtectedSessionStorage(
Substitute.For(),
Substitute.For()),
AuthState,
Substitute.For());
provider.GetAuthenticationStateAsync().Returns(Task.FromResult(
new AuthenticationState(new System.Security.Claims.ClaimsPrincipal(
new System.Security.Claims.ClaimsIdentity("test")))));
return provider;
}
}
///
/// In-memory HttpMessageHandler that dispatches requests to registered
/// responders based on HTTP method and path substrings. Robust against
/// parallel calls (unlike a FIFO queue).
///
public sealed class RoutedHandler : HttpMessageHandler
{
private readonly List<(HttpMethod Method, string PathContains, Func Responder)> _routes = [];
/// All requests received, for assertions.
public List Requests { get; } = [];
public void On(HttpMethod method, string pathContains, Func 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));
/// Convenience for GET routes returning a JSON body.
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 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);
}
}