using Heimdall.Agent.Services; 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(), Substitute.For>()); 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(), Substitute.For>()); // 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(), Substitute.For>(), 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); } } }