Files
Heimdall/tests/Heimdall.Agent.Tests/DetectionReporterServiceTests.cs
T
arnaud.dartois edecb601e3
Heimdall Gitea / Detect CI scope (pull_request) Successful in 6s
Heimdall Gitea / Build and tests (pull_request) Failing after 9m5s
Heimdall Gitea / Build and scan server image (pull_request) Skipped
Heimdall Gitea / Build and scan agent image (pull_request) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (pull_request) Skipped
Heimdall Gitea / Publish Docker Hub latest tags (pull_request) Skipped
Heimdall Gitea / Publish versioned release (pull_request) Skipped
Heimdall Gitea / CI policy (pull_request) Failing after 42s
feat(recordings): add event-triggered camera capture
2026-11-05 18:31:11 +01:00

207 lines
9.4 KiB
C#

using System.Globalization;
using Heimdall.Agent.Services;
using Heimdall.Domain.Entities;
using Heimdall.Domain.Enums;
using Microsoft.Data.Sqlite;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NSubstitute;
using Shouldly;
namespace Heimdall.Agent.Tests;
public class DetectionReporterServiceTests
{
[Theory]
[InlineData("person", EventType.PersonDetected)]
[InlineData("car", EventType.VehicleDetected)]
[InlineData("truck", EventType.VehicleDetected)]
[InlineData("bus", EventType.VehicleDetected)]
[InlineData("motorcycle", EventType.VehicleDetected)]
[InlineData("cat", null)]
[InlineData("dog", null)]
[InlineData("bottle", EventType.MotionDetected)]
[InlineData("Person", EventType.PersonDetected)]
public void MapDetectionToEventType_MapsKnownLabels(string label, EventType? expected)
{
DetectionReporterService.MapDetectionToEventType(label).ShouldBe(expected);
}
[Fact]
public async Task ReportAsync_UnregisteredAgent_ReturnsFalse()
{
var state = new AgentState { AgentId = Guid.Empty, ApiKey = "" };
var reporter = new DetectionReporterService(
state,
Substitute.For<IHttpClientFactory>(),
Substitute.For<ILogger<DetectionReporterService>>());
var sent = await reporter.ReportAsync(
Guid.NewGuid(), EventType.MotionDetected, 0.9, "motion");
sent.ShouldBeFalse();
reporter.FailedReports.ShouldBe(0);
}
[Fact]
public void ReportAsync_Unregistered_DoesNotThrow()
{
var state = new AgentState { AgentId = Guid.Empty, ApiKey = "" };
var reporter = new DetectionReporterService(
state,
Substitute.For<IHttpClientFactory>(),
Substitute.For<ILogger<DetectionReporterService>>());
// Pas d'appel réseau possible sans agent → ne doit pas crasher.
var task = reporter.ReportAsync(Guid.NewGuid(), EventType.PersonDetected, 0.8, "person");
task.IsCompleted.ShouldBeTrue();
}
[Fact]
public async Task ReportAsync_PersistsSnapshotWithPendingEvent()
{
var directory = Path.Combine(Path.GetTempPath(), $"heimdall-snapshot-outbox-{Guid.NewGuid():N}");
try
{
var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = "test-key" };
using var reporter = new DetectionReporterService(state,
Substitute.For<IHttpClientFactory>(),
Substitute.For<ILogger<DetectionReporterService>>(),
Options.Create(new Heimdall.Agent.AgentOptions { StateDirectory = directory }));
var jpeg = new byte[] { 0xff, 0xd8, 0xff, 0xd9 };
(await reporter.ReportAsync(Guid.NewGuid(), EventType.PersonDetected,
0.9, "person", snapshotJpeg: jpeg)).ShouldBeTrue();
await using var db = new SqliteConnection($"Data Source={Path.Combine(directory, "agent-events.db")}");
await db.OpenAsync();
await using var command = db.CreateCommand();
command.CommandText = "SELECT snapshot_jpeg FROM pending_detection_events LIMIT 1;";
((byte[])(await command.ExecuteScalarAsync())!).ShouldBe(jpeg);
}
finally
{
if (Directory.Exists(directory)) Directory.Delete(directory, recursive: true);
}
}
[Fact]
public async Task ReportAsync_EnabledEventRecordingPersistsTriggerUntilAfterPostRoll()
{
var directory = Path.Combine(Path.GetTempPath(), $"heimdall-event-recording-{Guid.NewGuid():N}");
try
{
var cameraId = Guid.NewGuid();
var occurredAt = DateTime.UtcNow;
var options = Options.Create(new AgentOptions
{
StateDirectory = directory,
RecordingEventPostRollSeconds = 20
});
var cameras = new CameraConfigStore();
cameras.SetLocalFallback([new AgentCameraConfig(cameraId, "Door", "rtsp://camera/stream", null,
true, EventRecordingEnabled: true)]);
var triggers = new RecordingTriggerStore(options);
using var reporter = new DetectionReporterService(
new AgentState { AgentId = Guid.NewGuid(), ApiKey = "test-key" },
Substitute.For<IHttpClientFactory>(), Substitute.For<ILogger<DetectionReporterService>>(),
options, cameras, triggers);
(await reporter.ReportAsync(cameraId, EventType.PersonDetected, 0.9, "person", occurredAt: occurredAt))
.ShouldBeTrue();
var status = await triggers.GetStatusAsync(cameraId);
status.IsActive.ShouldBeTrue();
status.FirstTriggeredAtUtc.ShouldBe(CameraEvent.NormalizeOccurredAt(occurredAt));
}
finally
{
if (Directory.Exists(directory)) Directory.Delete(directory, recursive: true);
}
}
[Fact]
public async Task ManualSnapshots_KeepRequestIds_WithoutCooldown()
{
var directory = Path.Combine(Path.GetTempPath(), $"heimdall-manual-outbox-{Guid.NewGuid():N}");
try
{
var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = "test-key" };
using var reporter = new DetectionReporterService(state,
Substitute.For<IHttpClientFactory>(), Substitute.For<ILogger<DetectionReporterService>>(),
Options.Create(new Heimdall.Agent.AgentOptions { StateDirectory = directory }));
var cameraId = Guid.NewGuid();
var firstId = Guid.NewGuid();
var secondId = Guid.NewGuid();
var jpeg = new byte[] { 0xff, 0xd8, 0xff, 0xd9 };
(await reporter.ReportAsync(cameraId, EventType.ManualSnapshot, 1, "manual",
snapshotJpeg: jpeg, eventId: firstId)).ShouldBeTrue();
(await reporter.ReportAsync(cameraId, EventType.ManualSnapshot, 1, "manual",
snapshotJpeg: jpeg, eventId: secondId)).ShouldBeTrue();
await using var db = new SqliteConnection($"Data Source={Path.Combine(directory, "agent-events.db")}");
await db.OpenAsync();
await using var command = db.CreateCommand();
command.CommandText = "SELECT event_id FROM pending_detection_events ORDER BY event_id;";
await using var reader = await command.ExecuteReaderAsync();
var ids = new List<Guid>();
while (await reader.ReadAsync()) ids.Add(Guid.Parse(reader.GetString(0)));
ids.OrderBy(id => id).ShouldBe(new[] { firstId, secondId }.OrderBy(id => id));
}
finally
{
if (Directory.Exists(directory)) Directory.Delete(directory, recursive: true);
}
}
[Fact]
public async Task ReportAsync_AdoptsLegacyOutboxAndPreservesQueuedEvents()
{
var directory = Path.Combine(Path.GetTempPath(), $"heimdall-legacy-outbox-{Guid.NewGuid():N}");
Directory.CreateDirectory(directory);
var databasePath = Path.Combine(directory, "agent-events.db");
try
{
await using (var database = new SqliteConnection($"Data Source={databasePath}"))
{
await database.OpenAsync();
await using var command = database.CreateCommand();
command.CommandText = """
CREATE TABLE pending_detection_events (
event_id TEXT PRIMARY KEY NOT NULL, event_type INTEGER NOT NULL,
priority INTEGER NOT NULL, payload_json TEXT NOT NULL, created_at TEXT NOT NULL,
attempts INTEGER NOT NULL DEFAULT 0);
CREATE INDEX ix_pending_detection_events_priority_created
ON pending_detection_events(priority DESC, created_at);
CREATE TABLE dead_letter_detection_events (
event_id TEXT PRIMARY KEY NOT NULL, payload_json TEXT NOT NULL,
created_at TEXT NOT NULL, last_error TEXT NOT NULL, attempts INTEGER NOT NULL);
INSERT INTO pending_detection_events
(event_id, event_type, priority, payload_json, created_at, attempts)
VALUES ('11111111-1111-4111-8111-111111111111', 0, 1, '{}', '2026-01-01T00:00:00Z', 0);
PRAGMA user_version=1;
""";
await command.ExecuteNonQueryAsync();
}
using var reporter = new DetectionReporterService(new AgentState { AgentId = Guid.NewGuid(), ApiKey = "test-key" },
Substitute.For<IHttpClientFactory>(), Substitute.For<ILogger<DetectionReporterService>>(),
Options.Create(new Heimdall.Agent.AgentOptions { StateDirectory = directory }));
(await reporter.ReportAsync(Guid.NewGuid(), EventType.PersonDetected, 0.9, "person")).ShouldBeTrue();
reporter.FailedReports.ShouldBe(0);
await using var verify = new SqliteConnection($"Data Source={databasePath};Mode=ReadOnly");
await verify.OpenAsync();
await using var check = verify.CreateCommand();
check.CommandText = "SELECT COUNT(*) FROM pending_detection_events WHERE event_id='11111111-1111-4111-8111-111111111111' AND snapshot_jpeg IS NULL;";
Convert.ToInt32(await check.ExecuteScalarAsync(), CultureInfo.InvariantCulture).ShouldBe(1);
}
finally
{
if (Directory.Exists(directory)) Directory.Delete(directory, recursive: true);
}
}
}