Files
Heimdall/tests/Heimdall.Web.Tests/Components/Pages/PageTestBase.cs
T
Arnaud Dartois 34a3dd4232 test(web): tests bUnit des pages IHM + infrastructure de test MudBlazor
Pages couvertes : Login, Register, Dashboard, SitesPage, SiteDetail,
CamerasPage (+ AuthState, HeimdallAuthStateProvider) — 105 tests Web verts.

Infrastructure nécessaire pour rendre les pages testables avec bUnit :
- MudTestBase : JSInterop en mode Loose + wrapper générique
  IAsyncDisposable→IDisposable (Castle DynamicProxy) pour les services
  MudBlazor (PopoverService, PointerEventsNoneService...) qui cassent le
  Dispose synchrone de bUnit
- HostWithProviders.razor : fournit MudPopoverProvider + MudDialogProvider
  — sans eux les MudDialog inline des pages ne sont jamais rendus
- PageTestBase.RenderPage<T> : rend les pages dans ce host
- bunit 2.7.2 → 2.9.0, AngleSharp → 1.7.0, SDK Razor pour les .razor locaux

Correctifs de tests : ShouldContain avec prédicat (sous-chaîne au lieu
d'égalité stricte sur les messages snackbar), .Input()/.Change() selon
Immediate des champs, format P0 (87% sans espace), index des boutons
d'action (copier vs supprimer).
2026-08-10 12:46:15 +02:00

151 lines
6.1 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.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; }
protected PageTestBase()
{
// ILogger<T> (required by Login page) — silent by default
Services.AddLogging();
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);
}
/// <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&lt;T&gt;() 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);
}
}