test(qa): cover agent event notification flow end to end #105

Merged
arnaud.dartois merged 7 commits from test/qa01-notification-flow into main 2026-10-25 19:24:24 +01:00
7 changed files with 307 additions and 22 deletions

No files matched your search

@@ -2,23 +2,39 @@
@implements IAsyncDisposable
@inject NotificationsHubClient Hub
@inject NavigationManager Navigation
@inject AuthenticationStateProvider AuthenticationStateProvider
@inject Heimdall.Web.Services.UiText Text
<MudTooltip Text="@Text["SharedNotificationBadge_Title"]">
<MudIconButton Icon="@Icons.Material.Filled.Notifications" Color="Color.Inherit" aria-label="@Text["SharedNotificationBadge_Title"]"
OnClick="@(() => Navigation.NavigateTo("/events"))">
@if (Hub.UnreadCount > 0)
{
<MudBadge Color="Color.Error" Overlap="true" Bordered="true" Content="@Hub.UnreadCount" />
}
</MudIconButton>
<MudBadge Color="Color.Error" Overlap="true" Bordered="true" Content="@Hub.UnreadCount"
Visible="@(Hub.UnreadCount > 0)">
<MudIconButton Icon="@Icons.Material.Filled.Notifications" Color="Color.Inherit"
aria-label="@Text["SharedNotificationBadge_Title"]"
OnClick="@(() => Navigation.NavigateTo("/events"))" />
</MudBadge>
</MudTooltip>
@code {
protected override async Task OnInitializedAsync()
{
Hub.UnreadCountChanged += OnUnreadChanged;
AuthenticationStateProvider.AuthenticationStateChanged += OnAuthenticationStateChanged;
await Hub.StartAsync();
await Hub.RefreshUnreadCountAsync();
}
private void OnAuthenticationStateChanged(Task<AuthenticationState> authenticationStateTask)
{
_ = InvokeAsync(async () =>
{
var authenticationState = await authenticationStateTask;
if (authenticationState.User.Identity?.IsAuthenticated == true)
{
await Hub.StartAsync();
await Hub.RefreshUnreadCountAsync();
}
StateHasChanged();
});
}
private void OnUnreadChanged(int _) => InvokeAsync(StateHasChanged);
@@ -26,6 +42,7 @@
public async ValueTask DisposeAsync()
{
Hub.UnreadCountChanged -= OnUnreadChanged;
AuthenticationStateProvider.AuthenticationStateChanged -= OnAuthenticationStateChanged;
await Hub.DisposeAsync();
}
}
+11 -2
View File
@@ -20,9 +20,16 @@ public class NotificationsHub : Hub
private readonly ILogger<NotificationsHub> _logger;
private readonly ResourceAccess _access;
private readonly LiveSubscriptions _subscriptions;
private readonly INotificationService _notifications;
public NotificationsHub(ILogger<NotificationsHub> logger, ResourceAccess access, LiveSubscriptions subscriptions)
{ _logger = logger; _access = access; _subscriptions = subscriptions; }
public NotificationsHub(ILogger<NotificationsHub> logger, ResourceAccess access,
LiveSubscriptions subscriptions, INotificationService notifications)
{
_logger = logger;
_access = access;
_subscriptions = subscriptions;
_notifications = notifications;
}
/// <summary>
/// Clients call this to join their personal notification channel.
@@ -36,6 +43,8 @@ public class NotificationsHub : Hub
var userId = requester.Id.ToString();
_subscriptions.Join("notifications", Context.ConnectionId, userId, Context.User!);
_logger.LogDebug("Client {ConnectionId} joined personal notifications for user {UserId}", Context.ConnectionId, userId);
var unreadCount = await _notifications.GetUnreadCountAsync(requester.Id, Context.ConnectionAborted);
await Clients.Caller.SendAsync("UnreadCount", new { count = unreadCount }, Context.ConnectionAborted);
}
public Task LeavePersonalNotifications()
@@ -124,6 +124,16 @@ public class HeimdallApiClient : IDisposable
return await client.GetFromJsonAsync<UserItem>("api/users/me", Json);
}
public async Task<int> GetUnreadNotificationCountAsync()
{
using var response = await CreateClient().GetAsync("api/notifications/unread-count");
if (!response.IsSuccessStatusCode)
return 0;
var result = await response.Content.ReadFromJsonAsync<Heimdall.Application.DTOs.UnreadCountDto>(Json);
return result?.Count ?? 0;
}
public async Task<bool> UpdateMyProfileAsync(string displayName, string? theme, string? language)
{
var client = CreateClient();
@@ -1,3 +1,4 @@
using System.Text.Json;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.SignalR.Client;
@@ -6,13 +7,13 @@ namespace Heimdall.Web.Services;
/// <summary>
/// Client hub SignalR pour les notifications temps réel (badge compteur).
/// S'abonne au groupe personnel "notif_{userId}" et expose l'événement
/// <see cref="UnreadCountChanged"/>. Le polling est le fallback : si la
/// connexion échoue (pas de JWT en session cookie, hub indisponible), le
/// badge reste silencieux sans casser l'UI.
/// <see cref="UnreadCountChanged"/>. Un chargement API initial garantit le
/// compteur même si la connexion temps réel n'est pas encore disponible.
/// </summary>
public class NotificationsHubClient : IAsyncDisposable, IDisposable
{
private readonly AuthState _authState;
private readonly HeimdallApiClient _api;
private readonly NavigationManager _navigation;
private readonly ILogger<NotificationsHubClient> _logger;
private HubConnection? _connection;
@@ -20,10 +21,12 @@ public class NotificationsHubClient : IAsyncDisposable, IDisposable
public NotificationsHubClient(
AuthState authState,
HeimdallApiClient api,
NavigationManager navigation,
ILogger<NotificationsHubClient> logger)
{
_authState = authState;
_api = api;
_navigation = navigation;
_logger = logger;
}
@@ -33,6 +36,20 @@ public class NotificationsHubClient : IAsyncDisposable, IDisposable
public event Action<int>? UnreadCountChanged;
public async Task RefreshUnreadCountAsync()
{
try
{
var count = await _api.GetUnreadNotificationCountAsync();
UnreadCount = count;
UnreadCountChanged?.Invoke(count);
}
catch (Exception ex)
{
_logger.LogDebug(ex, "NotificationsHubClient: chargement initial du compteur impossible");
}
}
public async Task StartAsync()
{
if (_started || !_authState.IsLoggedIn)
@@ -52,18 +69,18 @@ public class NotificationsHubClient : IAsyncDisposable, IDisposable
.WithAutomaticReconnect()
.Build();
_connection.On<object>("UnreadCount", (payload) =>
_connection.On<JsonElement>("UnreadCount", (payload) =>
{
try
if (payload.ValueKind != JsonValueKind.Object ||
!payload.TryGetProperty("count", out var countElement) ||
!countElement.TryGetInt32(out var count) || count < 0)
{
var count = (int)((IDictionary<string, object>)payload)["count"];
UnreadCount = count;
UnreadCountChanged?.Invoke(count);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "NotificationsHubClient: UnreadCount payload inattendu");
_logger.LogWarning("NotificationsHubClient: unread count payload inattendu");
return;
}
UnreadCount = count;
UnreadCountChanged?.Invoke(count);
});
_connection.On<object>("NewNotification", (_) =>
@@ -0,0 +1,231 @@
using System.Globalization;
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using Heimdall.Domain.Enums;
using Heimdall.Infrastructure.Data;
using Heimdall.TestCommon;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Playwright;
using Shouldly;
namespace Heimdall.E2E.Tests.Pages;
public sealed class DetectionFlowTests(PostgreSqlContainerFixture postgres) : E2ETestBase(postgres)
{
private const string SnapshotJpegBase64 = "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCAAgADADASIAAhEBAxEB/8QAFQABAQAAAAAAAAAAAAAAAAAAAAb/xAAUEAEAAAAAAAAAAAAAAAAAAAAA/8QAFQEBAQAAAAAAAAAAAAAAAAAAAAX/xAAUEQEAAAAAAAAAAAAAAAAAAAAA/9oADAMBAAIRAxEAPwCCAWkoAAAAAAAAAB//2Q==";
[Fact]
public async Task Assigned_agent_event_is_stored_notified_and_visible_only_with_camera_access()
{
var storageRoot = Path.Combine(Path.GetTempPath(), $"heimdall-e2e-storage-{Guid.NewGuid():N}");
var admin = new HttpClient { BaseAddress = new Uri(BaseUrl) };
admin.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", await LoginViaApiAsync());
string? originalStoragePath = null;
string? originalStorageProvider = null;
try
{
var storedPath = await admin.GetAsync("api/settings/storage.local.path");
storedPath.StatusCode.ShouldBe(HttpStatusCode.OK);
var setting = await storedPath.Content.ReadFromJsonAsync<JsonElement>();
originalStoragePath = setting.GetProperty("value").GetString();
var providerResponse = await admin.GetAsync("api/settings/storage.provider");
providerResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
var providerSetting = await providerResponse.Content.ReadFromJsonAsync<JsonElement>();
originalStorageProvider = providerSetting.GetProperty("value").GetString();
(await admin.PutAsJsonAsync("api/settings/storage.provider", new { value = "Local" }))
.StatusCode.ShouldBe(HttpStatusCode.OK);
(await admin.PutAsJsonAsync("api/settings/storage.local.path", new { value = storageRoot }))
.StatusCode.ShouldBe(HttpStatusCode.OK);
var initialUnreadResponse = await admin.GetAsync("api/notifications/unread-count");
initialUnreadResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
var initialUnread = (await initialUnreadResponse.Content.ReadFromJsonAsync<JsonElement>())
.GetProperty("count").GetInt32();
var siteId = await CreateSiteAsync(admin, "QA source");
var otherSiteId = await CreateSiteAsync(admin, "QA other");
var agent = await RegisterOnlineAgentAsync(admin, siteId);
var assignedCameraId = await CreateCameraAsync(admin, siteId, "QA assigned camera");
var otherCameraId = await CreateCameraAsync(admin, otherSiteId, "QA other-site camera");
(await admin.PostAsJsonAsync("api/assignments", new { cameraId = assignedCameraId, agentId = agent.Id }))
.StatusCode.ShouldBe(HttpStatusCode.OK);
var viewerEmail = $"qa-flow-{Guid.NewGuid():N}@heimdall.test";
const string viewerPassword = "QaFlowViewer123!";
var userResponse = await admin.PostAsJsonAsync("api/users", new
{
email = viewerEmail,
password = viewerPassword,
displayName = "QA Flow Viewer",
roles = new[] { "Viewer" }
});
userResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
var viewerUserId = (await userResponse.Content.ReadFromJsonAsync<JsonElement>()).GetProperty("id").GetGuid();
await ConfirmUserAsync(viewerEmail);
using var viewer = new HttpClient { BaseAddress = new Uri(BaseUrl) };
viewer.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Bearer", await LoginViaApiAsync(viewerEmail, viewerPassword));
(await viewer.GetAsync($"api/cameras/{assignedCameraId}")).StatusCode.ShouldBe(HttpStatusCode.Forbidden);
(await viewer.GetAsync($"api/cameras/{otherCameraId}")).StatusCode.ShouldBe(HttpStatusCode.Forbidden);
var grant = await admin.PostAsJsonAsync("api/user-camera-access", new
{
userId = viewerUserId,
siteId,
cameraId = assignedCameraId
});
grant.StatusCode.ShouldBe(HttpStatusCode.OK);
(await viewer.GetAsync($"api/cameras/{assignedCameraId}")).StatusCode.ShouldBe(HttpStatusCode.OK);
(await viewer.GetAsync($"api/cameras/{otherCameraId}")).StatusCode.ShouldBe(HttpStatusCode.Forbidden);
using var agentClient = AgentClient(agent.ApiKey);
var occurredAt = DateTime.UtcNow;
var eventId = Guid.NewGuid();
var label = $"qa-flow-{Guid.NewGuid():N}";
var eventRequest = new
{
cameraId = assignedCameraId,
type = (int)EventType.PersonDetected,
confidence = 0.97,
label,
occurredAt,
eventId
};
(await agentClient.PostAsJsonAsync("api/events", new
{
cameraId = otherCameraId,
type = (int)EventType.PersonDetected,
confidence = 0.9,
label = "wrong-site"
})).StatusCode.ShouldBe(HttpStatusCode.Forbidden);
var createdEvent = await agentClient.PostAsJsonAsync("api/events", eventRequest);
createdEvent.StatusCode.ShouldBe(HttpStatusCode.OK);
var eventResponse = await createdEvent.Content.ReadFromJsonAsync<JsonElement>();
eventResponse.GetProperty("id").GetGuid().ShouldBe(eventId);
// The agent outbox may retry an accepted event. Its deterministic ID must
// preserve a single event and a single in-app notification per recipient.
(await agentClient.PostAsJsonAsync("api/events", eventRequest)).StatusCode.ShouldBe(HttpStatusCode.OK);
using var image = new ByteArrayContent(Convert.FromBase64String(SnapshotJpegBase64));
image.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
var uploaded = await agentClient.PutAsync($"api/events/{eventId:D}/snapshot/content", image);
uploaded.StatusCode.ShouldBe(HttpStatusCode.OK);
foreach (var client in new[] { admin, viewer })
{
var notificationsResponse = await client.GetAsync("api/notifications?isRead=false&page=1&pageSize=100");
notificationsResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
var notifications = await notificationsResponse.Content.ReadFromJsonAsync<JsonElement>();
var matchingNotifications = notifications.GetProperty("items").EnumerateArray()
.Where(item => item.GetProperty("cameraId").GetGuid() == assignedCameraId)
.ToArray();
matchingNotifications.Length.ShouldBe(1);
matchingNotifications[0].GetProperty("eventType").GetString().ShouldBe(nameof(EventType.PersonDetected));
}
(await viewer.GetAsync($"api/events/{eventId:D}")).StatusCode.ShouldBe(HttpStatusCode.OK);
(await viewer.GetAsync($"api/events/{eventId:D}/snapshot/content")).StatusCode.ShouldBe(HttpStatusCode.OK);
(await viewer.GetAsync($"api/events/{Guid.NewGuid():D}/snapshot/content")).StatusCode
.ShouldBe(HttpStatusCode.Forbidden);
await LoginViaUiAsync();
await Page.Locator(".mud-badge").WaitForAsync(new() { Timeout = 15000 });
(await Page.Locator(".mud-badge").First.TextContentAsync() ?? string.Empty)
.ShouldContain((initialUnread + 1).ToString(CultureInfo.InvariantCulture));
await GotoWithCircuitAsync("/events");
await Page.GetByText(label, new() { Exact = true }).WaitForAsync(new() { Timeout = 15000 });
}
finally
{
if (originalStorageProvider is not null)
{
try
{
var restore = await admin.PutAsJsonAsync("api/settings/storage.provider",
new { value = originalStorageProvider });
restore.Dispose();
}
catch { /* Keep test cleanup from hiding the original failure. */ }
}
if (originalStoragePath is not null)
{
try
{
var restore = await admin.PutAsJsonAsync("api/settings/storage.local.path",
new { value = originalStoragePath });
restore.Dispose();
}
catch { /* Keep test cleanup from hiding the original failure. */ }
}
admin.Dispose();
if (Directory.Exists(storageRoot)) Directory.Delete(storageRoot, recursive: true);
}
}
private static async Task<Guid> CreateSiteAsync(HttpClient admin, string name)
{
var response = await admin.PostAsJsonAsync("api/sites", new { name = $"{name} {Guid.NewGuid():N}", timezone = "UTC" });
response.StatusCode.ShouldBe(HttpStatusCode.OK);
return (await response.Content.ReadFromJsonAsync<JsonElement>()).GetProperty("id").GetGuid();
}
private static async Task<Guid> CreateCameraAsync(HttpClient admin, Guid siteId, string name)
{
var response = await admin.PostAsJsonAsync("api/cameras", new
{
siteId,
name,
rtspUrl = $"rtsp://127.0.0.1/{Guid.NewGuid():N}"
});
response.StatusCode.ShouldBe(HttpStatusCode.OK);
return (await response.Content.ReadFromJsonAsync<JsonElement>()).GetProperty("id").GetGuid();
}
private async Task<(Guid Id, string ApiKey)> RegisterOnlineAgentAsync(HttpClient admin, Guid siteId)
{
var tokenResponse = await admin.PostAsync($"api/sites/{siteId}/tokens", null);
tokenResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
var token = (await tokenResponse.Content.ReadFromJsonAsync<JsonElement>()).GetProperty("token").GetString()!;
var registration = await admin.PostAsJsonAsync("api/agents/register", new
{
token,
hostname = $"qa-flow-agent-{Guid.NewGuid():N}",
version = "1.0.0-test"
});
registration.StatusCode.ShouldBe(HttpStatusCode.OK);
var agent = await registration.Content.ReadFromJsonAsync<JsonElement>();
var id = agent.GetProperty("agentId").GetGuid();
var apiKey = agent.GetProperty("apiKey").GetString()!;
using var agentClient = AgentClient(apiKey);
var heartbeat = await agentClient.PostAsJsonAsync($"api/agents/{id:D}/heartbeat", new
{
publicIp = "127.0.0.1",
cpuCores = 4,
memoryMb = 4096
});
heartbeat.StatusCode.ShouldBe(HttpStatusCode.OK);
return (id, apiKey);
}
private async Task ConfirmUserAsync(string email)
{
await using var scope = App.Services.CreateAsyncScope();
var dbFactory = scope.ServiceProvider.GetRequiredService<IDbContextFactory<AppDbContext>>();
await using var db = await dbFactory.CreateDbContextAsync();
var user = await db.Users.SingleAsync(candidate => candidate.Email == email);
user.EmailConfirmed = true;
await db.SaveChangesAsync();
}
private HttpClient AgentClient(string apiKey)
{
var client = new HttpClient { BaseAddress = new Uri(BaseUrl) };
client.DefaultRequestHeaders.Add("X-API-Key", apiKey);
return client;
}
}
@@ -63,6 +63,7 @@ public abstract class PageTestBase : MudTestBase
Services.AddScoped(_ => Environment);
Services.AddScoped(sp => new NotificationsHubClient(
AuthState,
Api,
Services.GetRequiredService<NavigationManager>(),
Substitute.For<Microsoft.Extensions.Logging.ILogger<NotificationsHubClient>>()));
}
+1 -1
View File
@@ -30,7 +30,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant
- [ ] **AGENT-10** Tester charge, redémarrages rapides et arrêt FFmpeg/ONNX sous contrainte sur matériel représentatif.
- [ ] **Toggle caméra #59/#199** L’interface détail empêche maintenant les doubles clics pendant le POST et garde un verrou côté méthode. Restent à prouver sur Agent connecté que OFF arrête capture et libère les ressources en moins de 2 s, ON reprend avec backoff en moins de 10 s, et que l’état survit au redémarrage.
- [ ] **Accès caméra #141** La PR #65 ajoute les scénarios API de grant caméra direct, refus cross-camera, suppression logique et restrictions des routes groupes, ainsi que les tests du filtre d’affectations et des hubs après suppression logique ; sa CI est passée. La PR #88 ajoute le remplacement UI atomique, le chargement complet paginé, la protection du brouillon, et la révocation individuelle des accès excédant la limite de 500. La PR #100 ajoute un gate CI strict (>80 % de lignes par classe ciblée) et étend les tests Application, Infrastructure et Web. Le run PR #319 a mesuré : `CameraAccessService` 100 %, `ResourceAccess` 88,46 %, `ResourceAccessFilter` 82,54 %, `UserCameraAccessController` 83,33 % ; handlers/queries/mapping Application de 90 % à 100 %. Restent la validation produit des accès directs/groupes (#133/#134).
- [ ] **QA-01** Ajouter scénarios transversaux API → Agent → stockage → événement → UI → notification, dont périmètres de site et droits caméra ; mesurer couverture utile sans compter les tests ignorés comme succès.
- [x] **QA-01** Parcours E2E Playwright complet : Agent enregistré simulé, événement et reprise idempotente, snapshot dans un stockage local temporaire, notification persistée, droits caméra accordé/refusé par périmètre, puis affichage de l’événement et du compteur initial dans l’UI. Le run PR #313 a réussi les 35 E2E sans test ignoré, ainsi que les tests web et d’intégration affectés, le build et les scans des deux images. Le badge charge le compteur par API à l’initialisation et suit ensuite les mises à jour SignalR. Restent les validations caméra et Agent en environnement réel.
- [ ] Tester une restauration isolée PostgreSQL, objets et clés Data Protection ; fixer RPO/RTO et documenter la procédure mesurée.
## P2 — fonctionnalités et exploitation