Files
Heimdall/tests/Heimdall.Web.Tests/Services/HeimdallAuthStateProviderTests.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

104 lines
4.1 KiB
C#

using System.Security.Claims;
using Heimdall.Web.Services;
using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage;
using Microsoft.AspNetCore.Http;
using Microsoft.JSInterop;
using NSubstitute;
using Shouldly;
namespace Heimdall.Web.Tests.Services;
/// <summary>
/// Tests for HeimdallAuthStateProvider — focused on the cookie (SSR) and
/// anonymous paths. The ProtectedSessionStorage path requires a live Blazor
/// circuit (server-side Data Protection + JS interop) and is covered by the
/// E2E Playwright suite instead.
/// </summary>
public class HeimdallAuthStateProviderTests
{
private static HeimdallAuthStateProvider CreateProvider(
IHttpContextAccessor httpContextAccessor,
AuthState? authState = null)
{
// ProtectedSessionStorage is sealed and cannot be substituted; a real
// instance with a mocked IJSRuntime works fine because the storage
// path throws outside a live circuit and is caught by the provider.
var jsRuntime = Substitute.For<IJSRuntime>();
var storage = new ProtectedSessionStorage(jsRuntime, new FakeDataProtectionProvider());
return new HeimdallAuthStateProvider(
storage,
authState ?? new AuthState(),
httpContextAccessor);
}
private static IHttpContextAccessor CreateContextAccessor(ClaimsPrincipal? user = null)
{
var context = new DefaultHttpContext();
context.User = user ?? new ClaimsPrincipal(new ClaimsIdentity());
var accessor = Substitute.For<IHttpContextAccessor>();
accessor.HttpContext.Returns(context);
return accessor;
}
[Fact]
public async Task GetAuthenticationStateAsync_WithAuthenticatedCookie_ReturnsUserState()
{
var userId = Guid.NewGuid();
var principal = new ClaimsPrincipal(new ClaimsIdentity(
[
new Claim(ClaimTypes.NameIdentifier, userId.ToString()),
new Claim(ClaimTypes.Name, "Admin User"),
new Claim(ClaimTypes.Email, "admin@heimdall.test"),
new Claim(ClaimTypes.Role, "Admin")
], "Cookies"));
var authState = new AuthState();
var provider = CreateProvider(CreateContextAccessor(principal), authState);
var result = await provider.GetAuthenticationStateAsync();
result.User.Identity!.IsAuthenticated.ShouldBeTrue();
result.User.Identity!.AuthenticationType.ShouldBe("Cookies");
// The cookie principal is returned as-is
result.User.FindFirst(ClaimTypes.NameIdentifier)!.Value.ShouldBe(userId.ToString());
// AuthState is populated for downstream consumers
authState.IsLoggedIn.ShouldBeTrue();
authState.User!.Email.ShouldBe("admin@heimdall.test");
}
[Fact]
public async Task GetAuthenticationStateAsync_WithAnonymousUser_ReturnsAnonymous()
{
var provider = CreateProvider(CreateContextAccessor());
var result = await provider.GetAuthenticationStateAsync();
result.User.Identity!.IsAuthenticated.ShouldBeFalse();
}
[Fact]
public async Task GetAuthenticationStateAsync_WithoutHttpContext_ReturnsAnonymous()
{
var accessor = Substitute.For<IHttpContextAccessor>();
accessor.HttpContext.Returns((HttpContext?)null);
var provider = CreateProvider(accessor);
var result = await provider.GetAuthenticationStateAsync();
result.User.Identity!.IsAuthenticated.ShouldBeFalse();
}
}
/// <summary>Minimal IDataProtectionProvider for ProtectedBrowserStorage.</summary>
internal sealed class FakeDataProtectionProvider : Microsoft.AspNetCore.DataProtection.IDataProtectionProvider
{
public Microsoft.AspNetCore.DataProtection.IDataProtector CreateProtector(string purpose)
=> new FakeDataProtector();
}
internal sealed class FakeDataProtector : Microsoft.AspNetCore.DataProtection.IDataProtector
{
public byte[] Protect(byte[] plaintext) => plaintext;
public byte[] Unprotect(byte[] protectedData) => protectedData;
public Microsoft.AspNetCore.DataProtection.IDataProtector CreateProtector(string purpose) => this;
}