Files
Heimdall/tests/Heimdall.Agent.Tests/SnapshotPipelineServiceTests.cs
T
arnaud.dartois be1cb9b479
Heimdall Gitea / Detect CI scope (push) Successful in 5s
Heimdall Gitea / Build and tests (push) Successful in 21m23s
Heimdall Gitea / Build and scan server image (push) Skipped
Heimdall Gitea / Build and scan agent image (push) Successful in 10m36s
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Successful in 28m8s
Heimdall Gitea / Publish versioned installer release (push) Skipped
Heimdall Gitea / CI policy (push) Successful in 4s
Fix camera config reconciliation latency
Refs #157

Reconcile camera config changes immediately and strengthen the disposable toggle acceptance evidence.

Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-12 14:37:33 +01:00

194 lines
7.6 KiB
C#

using Heimdall.Agent.Services;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NSubstitute;
namespace Heimdall.Agent.Tests;
public class SnapshotPipelineServiceTests
{
private const string FfmpegNotFound = "/usr/bin/nonexistent-ffmpeg";
private static (SnapshotPipelineService Service, AgentState State, CameraConfigStore Store, CameraStreamService Streams, FrameAnalyzerService Analyzer, ICameraStatusReporter StatusReporter) CreatePipeline(
List<AgentCameraOptions>? cameras = null,
AnalysisMode analysisMode = AnalysisMode.Local,
string? brokerUrl = null)
{
var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = "test-key" };
var options = Options.Create(new AgentOptions
{
CentralUrl = "http://localhost:5000",
SiteToken = "test",
Cameras = cameras ?? [],
AnalysisMode = analysisMode,
BrokerUrl = brokerUrl,
});
var store = new CameraConfigStore();
var streams = new CameraStreamService(Substitute.For<ILogger<CameraStreamService>>(), FfmpegNotFound);
var analyzer = new FrameAnalyzerService(Substitute.For<ILogger<FrameAnalyzerService>>());
var statusReporter = Substitute.For<ICameraStatusReporter>();
var detectionReporter = Substitute.For<IDetectionReporter>();
var degradationManager = new PipelineDegradationManager(Substitute.For<ILogger<PipelineDegradationManager>>());
var metrics = new SystemMetricsProvider();
var service = new SnapshotPipelineService(new SnapshotPipelineServiceOptions(
state, options, store, streams, analyzer, new SceneStateTracker(), statusReporter, detectionReporter,
Substitute.For<ILogger<SnapshotPipelineService>>(),
DegradationManager: degradationManager, Metrics: metrics));
return (service, state, store, streams, analyzer, statusReporter);
}
[Fact]
public async Task StartStop_WithoutRegistration_StopsGracefully()
{
var (service, state, _, _, _, _) = CreatePipeline();
state.AgentId = Guid.Empty; // never registered
await service.StartAsync(CancellationToken.None);
var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(300));
await service.StopAsync(cts.Token);
state.AgentId.ShouldBe(Guid.Empty);
}
[Fact]
public async Task StartStop_WithNoCameras_DoesNotStartStreams()
{
var (service, _, _, streams, _, _) = CreatePipeline();
await service.StartAsync(CancellationToken.None);
try
{
await Task.Delay(200);
streams.ActiveStreamCount.ShouldBe(0);
}
finally
{
await service.StopAsync(CancellationToken.None);
}
}
[Fact]
public async Task StartStop_WithLocalCameras_PopulatesStoreFallback()
{
var cameras = new List<AgentCameraOptions>
{
new() { Name = "Cam 1", RtspUrl = "rtsp://cam1/stream" },
};
var (service, _, store, streams, _, _) = CreatePipeline(cameras);
await service.StartAsync(CancellationToken.None);
try
{
var deadline = DateTime.UtcNow.AddSeconds(5);
while (store.Cameras.Count == 0 && DateTime.UtcNow < deadline)
await Task.Delay(50);
// Local fallback applied to the store…
var camera = store.Cameras.ShouldHaveSingleItem();
camera.Name.ShouldBe("Cam 1");
camera.EffectiveRtspUrl.ShouldBe("rtsp://cam1/stream");
// …and capture attempted (ffmpeg missing → no active stream, no crash).
streams.ActiveStreamCount.ShouldBe(0);
}
finally
{
await service.StopAsync(CancellationToken.None);
}
}
[Fact]
public async Task CameraConfigChanged_ReconcilesWithoutWaitingForPeriodicSync()
{
var (service, _, store, streams, _, statusReporter) = CreatePipeline();
var cameraId = Guid.NewGuid();
await service.StartAsync(CancellationToken.None);
try
{
await Task.Delay(TimeSpan.FromMilliseconds(1100));
statusReporter.ClearReceivedCalls();
store.ReplaceCentral(new Dictionary<string, string>
{
[$"camera.{cameraId}.enabled"] = "true",
[$"camera.{cameraId}.rtsp"] = "rtsp://camera/test",
});
// The full periodic resync runs every 30 seconds. A config event
// must instead reconcile this transition on the event signal.
var deadline = DateTime.UtcNow.AddMilliseconds(500);
while (DateTime.UtcNow < deadline && !statusReporter.ReceivedCalls().Any())
await Task.Delay(10);
streams.ActiveStreamCount.ShouldBe(0); // FFmpeg is intentionally absent.
// Error is reported only after the enabled assignment is reconciled.
statusReporter.ReceivedCalls().Any(call =>
call.GetMethodInfo().Name == nameof(ICameraStatusReporter.ReportAsync) &&
Equals(call.GetArguments()[0], cameraId) &&
Equals(call.GetArguments()[1], "Error")).ShouldBeTrue();
}
finally
{
await service.StopAsync(CancellationToken.None);
}
}
[Fact]
public async Task SnapshotWrittenToChannel_IsForwardedToAnalyzer()
{
var (service, _, store, streams, analyzer, _) = CreatePipeline();
var id = Guid.NewGuid();
store.ReplaceCentral(new Dictionary<string, string>
{
[$"camera.{id}.enabled"] = "true",
[$"camera.{id}.profile"] = System.Text.Json.JsonSerializer.Serialize(new Heimdall.Application.DTOs.DetectionProfileDto { RequireMotionForAI = false })
});
using var image = new ImageMagick.MagickImage(ImageMagick.MagickColors.Black, 64, 64);
await service.StartAsync(CancellationToken.None);
try
{
await streams.SnapshotChannel.Writer.WriteAsync(
new Snapshot(id, DateTime.UtcNow, image.ToByteArray(ImageMagick.MagickFormat.Jpeg)));
var deadline = DateTime.UtcNow.AddSeconds(5);
while (analyzer.AnalyzedFrameCount == 0 && DateTime.UtcNow < deadline)
await Task.Delay(50);
// The frame reached the analyzer — real call, not just a counter.
// An unavailable model is never counted as a successful negative analysis.
service.SnapshotsProcessed.ShouldBe(0);
service.AnalysisFailures.ShouldBe(1);
analyzer.AnalyzedFrameCount.ShouldBe(1);
}
finally
{
await service.StopAsync(CancellationToken.None);
}
}
[Fact]
public async Task StopAsync_WithoutStart_DoesNotThrow()
{
var (service, _, _, _, _, _) = CreatePipeline();
await service.StopAsync(CancellationToken.None);
service.ShouldNotBeNull();
}
[Fact]
public void IsRemoteMode_LocalMode_ReturnsFalse()
{
var (service, _, _, _, _, _) = CreatePipeline(analysisMode: AnalysisMode.Local);
service.IsRemoteMode.ShouldBeFalse();
}
[Fact]
public void IsRemoteMode_RemoteMode_NoBroker_ReturnsFalse()
{
// Remote mode but no broker service injected → not actually remote
var (service, _, _, _, _, _) = CreatePipeline(analysisMode: AnalysisMode.Remote);
service.IsRemoteMode.ShouldBeFalse();
}
[Fact]
public void RemoteSubmissions_InitiallyZero()
{
var (service, _, _, _, _, _) = CreatePipeline();
service.RemoteSubmissions.ShouldBe(0);
service.RemoteFallbacks.ShouldBe(0);
}
}