test: add remaining handler tests for Users, Groups, Persons, Assignments, Discovery; more Agent + E2E tests

This commit is contained in:
Arnaud Dartois committed 2026-07-23 19:19:05 +00:00
1 parent a94afed6b5
commit 0745903fef
48 files changed
+2467 -1

No files matched your search

@@ -176,7 +176,7 @@ internal sealed class RetryDelayed : IRetryPolicy
public TimeSpan? NextRetryDelay(RetryContext context)
{
if (context.PreviousRetryCount < _delays.Length)
if (context.PreviousRetryCount >= 0 && context.PreviousRetryCount < _delays.Length)
return _delays[context.PreviousRetryCount];
// After exhausting specified delays, retry every 60 seconds
@@ -73,4 +73,54 @@ public class CameraStreamServiceTests
await service.StartStreamAsync(Guid.NewGuid(), "rtsp://localhost:8554/test", CancellationToken.None);
service.ActiveStreamCount.ShouldBe(0);
}
[Fact]
public async Task StartStreamAsync_PreCancelledToken_ThrowsTaskCanceled()
{
using var service = new CameraStreamService(Substitute.For<ILogger<CameraStreamService>>());
var cts = new CancellationTokenSource();
cts.Cancel();
var ex = await Record.ExceptionAsync(() =>
service.StartStreamAsync(Guid.NewGuid(), "rtsp://localhost:8554/test", cts.Token));
ex.ShouldBeOfType<TaskCanceledException>();
}
[Fact]
public async Task StartStreamAsync_AfterDispose_ThrowsObjectDisposed()
{
var service = new CameraStreamService(Substitute.For<ILogger<CameraStreamService>>());
service.Dispose();
var ex = await Record.ExceptionAsync(() =>
service.StartStreamAsync(Guid.NewGuid(), "rtsp://localhost:8554/test"));
ex.ShouldBeOfType<ObjectDisposedException>();
}
[Fact]
public async Task StartStreamAsync_ConcurrentDifferentCameras_AllFail()
{
using var service = new CameraStreamService(Substitute.For<ILogger<CameraStreamService>>());
var tasks = Enumerable.Range(0, 10)
.Select(i => service.StartStreamAsync(Guid.NewGuid(), $"rtsp://camera{i}/test"))
.ToArray();
var results = await Task.WhenAll(tasks);
results.ShouldAllBe(r => r == false);
}
[Fact]
public async Task StartStreamAsync_ThenStop_ActiveCountIsZero()
{
using var service = new CameraStreamService(Substitute.For<ILogger<CameraStreamService>>());
var id = Guid.NewGuid();
await service.StartStreamAsync(id, "rtsp://localhost:8554/test");
await service.StopStreamAsync(id);
service.ActiveStreamCount.ShouldBe(0);
}
[Fact]
public async Task StartStreamAsync_InvalidRtspUrl_ReturnsFalse()
{
using var service = new CameraStreamService(Substitute.For<ILogger<CameraStreamService>>());
var result = await service.StartStreamAsync(Guid.NewGuid(), "not-a-url");
result.ShouldBeFalse();
}
}
@@ -1,3 +1,4 @@
using System.Reflection;
using Heimdall.Agent.Services;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
@@ -55,4 +56,81 @@ public class ConfigReceiverServiceTests
var service = CreateService();
await service.StopAsync(CancellationToken.None);
}
[Fact]
public async Task ExecuteAsync_CancelledWhileWaitingForAgentId_StopsGracefully()
{
var state = new AgentState { AgentId = Guid.Empty };
var service = CreateService(state);
using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(100));
await service.StartAsync(cts.Token);
await service.StopAsync(CancellationToken.None);
}
[Fact]
public async Task ExecuteAsync_ConnectionRetriesThenCancels_StopsGracefully()
{
var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = "test-key" };
var service = CreateService(state);
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(2));
await service.StartAsync(cts.Token);
await service.StopAsync(CancellationToken.None);
}
[Fact]
public void ApplySetting_InvalidHeartbeatValue_DoesNotThrow()
{
var service = CreateService();
var method = typeof(ConfigReceiverService).GetMethod("ApplySetting",
BindingFlags.NonPublic | BindingFlags.Instance);
method.ShouldNotBeNull();
// Below minimum threshold (5)
Record.Exception(() => method.Invoke(service, ["heartbeat.interval.seconds", "3"]))
.ShouldBeNull();
// Non-numeric value
Record.Exception(() => method.Invoke(service, ["heartbeat.interval.seconds", "not-a-number"]))
.ShouldBeNull();
}
[Fact]
public void ApplySetting_KnownAndUnknownKeys_DoesNotThrow()
{
var service = CreateService();
var method = typeof(ConfigReceiverService).GetMethod("ApplySetting",
BindingFlags.NonPublic | BindingFlags.Instance);
method.ShouldNotBeNull();
Record.Exception(() => method.Invoke(service, ["log.level", "Debug"]))
.ShouldBeNull();
Record.Exception(() => method.Invoke(service, ["unknown.key", "some-value"]))
.ShouldBeNull();
}
[Fact]
public void ApplySetting_ValidHeartbeatInterval_DoesNotThrow()
{
var service = CreateService();
var method = typeof(ConfigReceiverService).GetMethod("ApplySetting",
BindingFlags.NonPublic | BindingFlags.Instance);
method.ShouldNotBeNull();
Record.Exception(() => method.Invoke(service, ["heartbeat.interval.seconds", "30"]))
.ShouldBeNull();
}
[Fact]
public async Task StartStop_MultipleTimes_DoesNotThrow()
{
var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = "test-key" };
var service = CreateService(state);
// First start/stop cycle
await service.StartAsync(CancellationToken.None);
await service.StopAsync(CancellationToken.None);
// Second start/stop cycle
await service.StartAsync(CancellationToken.None);
await service.StopAsync(CancellationToken.None);
}
}
@@ -116,4 +116,34 @@ public class HeartbeatRequestTests
json.ShouldContain("null");
}
[Fact]
public void GetHashCode_SameValues_AreEqual()
{
var a = new HeartbeatRequest("1.2.3.4", true, 50.0, 1024, 30.0, 3600);
var b = new HeartbeatRequest("1.2.3.4", true, 50.0, 1024, 30.0, 3600);
a.GetHashCode().ShouldBe(b.GetHashCode());
}
[Fact]
public void GetHashCode_DifferentValues_AreNotEqual()
{
var a = new HeartbeatRequest("1.2.3.4");
var b = new HeartbeatRequest("5.6.7.8");
a.GetHashCode().ShouldNotBe(b.GetHashCode());
}
[Fact]
public void JsonSerialization_AllNull_SerializesCorrectly()
{
var request = new HeartbeatRequest(null, CpuUsagePercent: null);
var json = JsonSerializer.Serialize(request);
var deserialized = JsonSerializer.Deserialize<HeartbeatRequest>(json);
deserialized.ShouldNotBeNull();
deserialized.PublicIp.ShouldBeNull();
deserialized.CpuUsagePercent.ShouldBeNull();
}
}
@@ -86,4 +86,29 @@ public class RetryDelayedTests
retry.NextRetryDelay(context).ShouldBe(TimeSpan.FromSeconds(3));
}
[Fact]
public void NextRetryDelay_NegativePreviousRetryCount_FallsBackToSixtySeconds()
{
var retry = new RetryDelayed(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(5));
retry.NextRetryDelay(new RetryContext { PreviousRetryCount = -1 })
.ShouldBe(TimeSpan.FromSeconds(60));
}
[Fact]
public void NextRetryDelay_LargeArrayOfDelays_WorksCorrectly()
{
var delays = Enumerable.Range(1, 10).Select(s => TimeSpan.FromSeconds(s)).ToArray();
var retry = new RetryDelayed(delays);
for (int i = 0; i < 10; i++)
{
retry.NextRetryDelay(new RetryContext { PreviousRetryCount = i })
.ShouldBe(delays[i]);
}
retry.NextRetryDelay(new RetryContext { PreviousRetryCount = 10 })
.ShouldBe(TimeSpan.FromSeconds(60));
}
}
@@ -109,4 +109,39 @@ public class SystemMetricsProviderTests
metrics.DiskUsagePercent.Value.ShouldBeLessThanOrEqualTo(100);
}
}
[Fact]
public void Collect_MemoryUsageBytes_IsPositive()
{
var provider = new SystemMetricsProvider();
var metrics = provider.Collect();
metrics.MemoryUsageBytes.ShouldNotBeNull();
metrics.MemoryUsageBytes.Value.ShouldBeGreaterThan(0);
}
[Fact]
public void Collect_CpuUsage_AfterSufficientDelay_StaysWithinRange()
{
var provider = new SystemMetricsProvider();
provider.Collect();
Thread.Sleep(600);
var metrics = provider.Collect();
if (metrics.CpuUsagePercent.HasValue)
{
metrics.CpuUsagePercent.Value.ShouldBeGreaterThanOrEqualTo(0);
metrics.CpuUsagePercent.Value.ShouldBeLessThanOrEqualTo(100);
}
}
[Fact]
public void Collect_TotalMemory_IsConsistent()
{
var provider = new SystemMetricsProvider();
var a = provider.Collect();
var b = provider.Collect();
if (a.TotalMemoryBytes.HasValue && b.TotalMemoryBytes.HasValue)
{
a.TotalMemoryBytes.Value.ShouldBe(b.TotalMemoryBytes.Value);
}
}
}
@@ -0,0 +1,37 @@
using Heimdall.Application.Assignments.Commands.AssignCamera;
using Heimdall.Application.Common;
using Heimdall.Application.Services;
using NSubstitute;
namespace Heimdall.Application.Tests.Handlers.Assignments;
public class AssignCameraHandlerTests
{
[Fact]
public async Task Assign_camera_should_return_success()
{
var service = Substitute.For<ICameraAssignmentService>();
service.AssignCameraAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(ServiceResult.Success());
var handler = new AssignCameraHandler(service);
var result = await handler.Handle(
new AssignCameraCommand(Guid.NewGuid(), Guid.NewGuid(), "manual"), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
}
[Fact]
public async Task Assign_camera_when_service_fails_should_return_failure()
{
var service = Substitute.For<ICameraAssignmentService>();
service.AssignCameraAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(ServiceResult.Failure("Camera already assigned"));
var handler = new AssignCameraHandler(service);
var result = await handler.Handle(
new AssignCameraCommand(Guid.NewGuid(), Guid.NewGuid(), "manual"), CancellationToken.None);
result.IsSuccess.ShouldBeFalse();
}
}
@@ -0,0 +1,54 @@
using Heimdall.Application.Assignments.Commands.AssignSite;
using Heimdall.Application.Common;
using Heimdall.Application.Services;
using NSubstitute;
namespace Heimdall.Application.Tests.Handlers.Assignments;
public class AssignSiteHandlerTests
{
[Fact]
public async Task Assign_site_should_return_count()
{
var service = Substitute.For<ICameraAssignmentService>();
service.AssignSiteCamerasAsync(Arg.Any<Guid>(), Arg.Any<AssignmentStrategy>(), Arg.Any<CancellationToken>())
.Returns(ServiceResult<int>.Success(5));
var handler = new AssignSiteHandler(service);
var result = await handler.Handle(
new AssignSiteCommand(Guid.NewGuid(), AssignmentStrategy.RoundRobin), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldBe(5);
}
[Fact]
public async Task Assign_site_with_different_strategies_should_pass_strategy()
{
var service = Substitute.For<ICameraAssignmentService>();
service.AssignSiteCamerasAsync(Arg.Any<Guid>(), AssignmentStrategy.GpuPriority, Arg.Any<CancellationToken>())
.Returns(ServiceResult<int>.Success(3));
var handler = new AssignSiteHandler(service);
var result = await handler.Handle(
new AssignSiteCommand(Guid.NewGuid(), AssignmentStrategy.GpuPriority), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldBe(3);
}
[Fact]
public async Task Assign_site_zero_cameras_should_return_zero()
{
var service = Substitute.For<ICameraAssignmentService>();
service.AssignSiteCamerasAsync(Arg.Any<Guid>(), Arg.Any<AssignmentStrategy>(), Arg.Any<CancellationToken>())
.Returns(ServiceResult<int>.Success(0));
var handler = new AssignSiteHandler(service);
var result = await handler.Handle(
new AssignSiteCommand(Guid.NewGuid(), AssignmentStrategy.LeastCameras), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldBe(0);
}
}
@@ -0,0 +1,61 @@
using Heimdall.Application.Assignments.Commands.Failover;
using Heimdall.Application.Common;
using Heimdall.Application.Services;
using Heimdall.Domain.Entities;
using NSubstitute;
namespace Heimdall.Application.Tests.Handlers.Assignments;
public class FailoverHandlerTests
{
[Fact]
public async Task Failover_should_return_reassigned_count()
{
var service = Substitute.For<ICameraAssignmentService>();
var siteId = Guid.NewGuid();
var cameras = new List<Camera>
{
new Camera(siteId, "Cam1"),
new Camera(siteId, "Cam2"),
};
service.FailoverAgentAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(ServiceResult<IReadOnlyList<Camera>>.Success(cameras));
var handler = new FailoverHandler(service);
var result = await handler.Handle(
new FailoverCommand(Guid.NewGuid()), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldBe(2);
}
[Fact]
public async Task Failover_no_cameras_should_return_zero()
{
var service = Substitute.For<ICameraAssignmentService>();
service.FailoverAgentAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(ServiceResult<IReadOnlyList<Camera>>.Success(new List<Camera>()));
var handler = new FailoverHandler(service);
var result = await handler.Handle(
new FailoverCommand(Guid.NewGuid()), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldBe(0);
}
[Fact]
public async Task Failover_when_service_fails_should_return_failure()
{
var service = Substitute.For<ICameraAssignmentService>();
service.FailoverAgentAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(ServiceResult<IReadOnlyList<Camera>>.Failure("Agent not found", 404));
var handler = new FailoverHandler(service);
var result = await handler.Handle(
new FailoverCommand(Guid.NewGuid()), CancellationToken.None);
result.IsSuccess.ShouldBeFalse();
result.StatusCode.ShouldBe(404);
}
}
@@ -0,0 +1,54 @@
using System.Reflection;
using Heimdall.Application.Assignments.Queries.GetActiveAssignment;
using Heimdall.Application.Common;
using Heimdall.Application.Services;
using Heimdall.Domain.Entities;
using NSubstitute;
namespace Heimdall.Application.Tests.Handlers.Assignments;
public class GetActiveAssignmentHandlerTests
{
private static CameraAssignment MakeAssignment(Guid cameraId, Guid agentId, string agentName)
{
var assignment = new CameraAssignment(cameraId, agentId, "manual");
var agent = new Agent(Guid.NewGuid(), agentName, "host", "1.0");
typeof(CameraAssignment).GetField("<Agent>k__BackingField",
BindingFlags.Instance | BindingFlags.NonPublic)!.SetValue(assignment, agent);
return assignment;
}
[Fact]
public async Task Get_active_assignment_should_return_assignment()
{
var cameraId = Guid.NewGuid();
var agentId = Guid.NewGuid();
var assignment = MakeAssignment(cameraId, agentId, "Agent 1");
var service = Substitute.For<ICameraAssignmentService>();
service.GetActiveAssignmentAsync(cameraId, Arg.Any<CancellationToken>()).Returns(assignment);
var handler = new GetActiveAssignmentHandler(service);
var result = await handler.Handle(new GetActiveAssignmentQuery(cameraId), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
result.Data.CameraId.ShouldBe(cameraId);
result.Data.AgentName.ShouldBe("Agent 1");
}
[Fact]
public async Task Get_active_assignment_no_assignment_should_return_null_success()
{
var service = Substitute.For<ICameraAssignmentService>();
service.GetActiveAssignmentAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns((CameraAssignment?)null);
var handler = new GetActiveAssignmentHandler(service);
var result = await handler.Handle(
new GetActiveAssignmentQuery(Guid.NewGuid()), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldBeNull();
}
}
@@ -0,0 +1,54 @@
using System.Reflection;
using Heimdall.Application.Assignments.Queries.GetAgentAssignments;
using Heimdall.Application.Common;
using Heimdall.Application.Services;
using Heimdall.Domain.Entities;
using NSubstitute;
namespace Heimdall.Application.Tests.Handlers.Assignments;
public class GetAgentAssignmentsHandlerTests
{
private static CameraAssignment MakeAssignment(Guid cameraId, Guid agentId, string agentName)
{
var assignment = new CameraAssignment(cameraId, agentId, "manual");
var agent = new Agent(Guid.NewGuid(), agentName, "host", "1.0");
typeof(CameraAssignment).GetField("<Agent>k__BackingField",
BindingFlags.Instance | BindingFlags.NonPublic)!.SetValue(assignment, agent);
return assignment;
}
[Fact]
public async Task Get_agent_assignments_should_return_assignments()
{
var agentId = Guid.NewGuid();
var assignment = MakeAssignment(Guid.NewGuid(), agentId, "Agent 1");
var service = Substitute.For<ICameraAssignmentService>();
service.GetAgentAssignmentsAsync(agentId, Arg.Any<CancellationToken>())
.Returns(new List<CameraAssignment> { assignment });
var handler = new GetAgentAssignmentsHandler(service);
var result = await handler.Handle(
new GetAgentAssignmentsQuery(agentId), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
result.Data.Count.ShouldBe(1);
}
[Fact]
public async Task Get_agent_assignments_empty_should_return_empty_list()
{
var service = Substitute.For<ICameraAssignmentService>();
service.GetAgentAssignmentsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(new List<CameraAssignment>());
var handler = new GetAgentAssignmentsHandler(service);
var result = await handler.Handle(
new GetAgentAssignmentsQuery(Guid.NewGuid()), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldBeEmpty();
}
}
@@ -0,0 +1,55 @@
using System.Reflection;
using Heimdall.Application.Assignments.Queries.GetCameraHistory;
using Heimdall.Application.Common;
using Heimdall.Application.Services;
using Heimdall.Domain.Entities;
using NSubstitute;
namespace Heimdall.Application.Tests.Handlers.Assignments;
public class GetCameraHistoryHandlerTests
{
private static CameraAssignment MakeAssignment(Guid cameraId, Guid agentId, string agentName, string reason)
{
var assignment = new CameraAssignment(cameraId, agentId, reason);
var agent = new Agent(Guid.NewGuid(), agentName, "host", "1.0");
typeof(CameraAssignment).GetField("<Agent>k__BackingField",
BindingFlags.Instance | BindingFlags.NonPublic)!.SetValue(assignment, agent);
return assignment;
}
[Fact]
public async Task Get_camera_history_should_return_history()
{
var cameraId = Guid.NewGuid();
var agentId = Guid.NewGuid();
var assignment = MakeAssignment(cameraId, agentId, "Agent 1", "failover");
var service = Substitute.For<ICameraAssignmentService>();
service.GetCameraHistoryAsync(cameraId, Arg.Any<CancellationToken>())
.Returns(new List<CameraAssignment> { assignment });
var handler = new GetCameraHistoryHandler(service);
var result = await handler.Handle(
new GetCameraHistoryQuery(cameraId), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
result.Data.Count.ShouldBe(1);
}
[Fact]
public async Task Get_camera_history_empty_should_return_empty_list()
{
var service = Substitute.For<ICameraAssignmentService>();
service.GetCameraHistoryAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(new List<CameraAssignment>());
var handler = new GetCameraHistoryHandler(service);
var result = await handler.Handle(
new GetCameraHistoryQuery(Guid.NewGuid()), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldBeEmpty();
}
}
@@ -0,0 +1,37 @@
using Heimdall.Application.Assignments.Commands.ReleaseCamera;
using Heimdall.Application.Common;
using Heimdall.Application.Services;
using NSubstitute;
namespace Heimdall.Application.Tests.Handlers.Assignments;
public class ReleaseCameraHandlerTests
{
[Fact]
public async Task Release_camera_should_return_success()
{
var service = Substitute.For<ICameraAssignmentService>();
service.ReleaseCameraAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(ServiceResult.Success());
var handler = new ReleaseCameraHandler(service);
var result = await handler.Handle(
new ReleaseCameraCommand(Guid.NewGuid()), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
}
[Fact]
public async Task Release_unassigned_camera_should_still_succeed()
{
var service = Substitute.For<ICameraAssignmentService>();
service.ReleaseCameraAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(ServiceResult.Success());
var handler = new ReleaseCameraHandler(service);
var result = await handler.Handle(
new ReleaseCameraCommand(Guid.NewGuid()), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
}
}
@@ -0,0 +1,49 @@
using Heimdall.Application.Discovery.Commands.BuildStreamUrls;
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using NSubstitute;
namespace Heimdall.Application.Tests.Handlers.Discovery;
public class BuildStreamUrlsHandlerTests
{
[Fact]
public async Task Build_stream_urls_should_return_urls()
{
var service = Substitute.For<ICameraDiscoveryService>();
var response = new StreamBuildResponse(["rtsp://admin:pass@192.168.1.100:554/stream1"]);
service.BuildStreamUrlsAsync(Arg.Any<StreamBuildRequest>(), Arg.Any<CancellationToken>())
.Returns(ServiceResult<StreamBuildResponse>.Success(response));
var handler = new BuildStreamUrlsCommandHandler(service);
var result = await handler.Handle(
new BuildStreamUrlsCommand(["p:onvif"], "192.168.1.100", "admin", "pass"),
CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
result.Data.Streams.ShouldNotBeEmpty();
}
[Fact]
public async Task Build_stream_urls_multiple_ids_should_return_multiple()
{
var service = Substitute.For<ICameraDiscoveryService>();
var response = new StreamBuildResponse([
"rtsp://admin:pass@192.168.1.100:554/stream1",
"rtsp://admin:pass@192.168.1.100:8554/stream2"
]);
service.BuildStreamUrlsAsync(Arg.Any<StreamBuildRequest>(), Arg.Any<CancellationToken>())
.Returns(ServiceResult<StreamBuildResponse>.Success(response));
var handler = new BuildStreamUrlsCommandHandler(service);
var result = await handler.Handle(
new BuildStreamUrlsCommand(["p:onvif", "b:hikvision"], "192.168.1.100", "admin", "pass",
1, [554, 8554]),
CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data!.Streams.Length.ShouldBe(2);
}
}
@@ -0,0 +1,23 @@
using Heimdall.Application.Discovery.Commands.CancelTestSession;
using Heimdall.Application.Common;
using Heimdall.Application.Services;
using NSubstitute;
namespace Heimdall.Application.Tests.Handlers.Discovery;
public class CancelTestSessionHandlerTests
{
[Fact]
public async Task Cancel_test_session_should_return_success()
{
var service = Substitute.For<ICameraDiscoveryService>();
service.CancelTestSessionAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(ServiceResult.Success());
var handler = new CancelTestSessionCommandHandler(service);
var result = await handler.Handle(
new CancelTestSessionCommand(Guid.NewGuid()), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
}
}
@@ -0,0 +1,46 @@
using Heimdall.Application.Discovery.Queries.CheckDuplicate;
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using NSubstitute;
namespace Heimdall.Application.Tests.Handlers.Discovery;
public class CheckDuplicateHandlerTests
{
[Fact]
public async Task Check_duplicate_should_return_not_duplicate()
{
var service = Substitute.For<ICameraDiscoveryService>();
var response = new CameraCheckResponse(false, null, null, null, null, null);
service.CheckDuplicateAsync(Arg.Any<CheckDuplicateRequest>(), Arg.Any<CancellationToken>())
.Returns(ServiceResult<CameraCheckResponse>.Success(response));
var handler = new CheckDuplicateQueryHandler(service);
var result = await handler.Handle(
new CheckDuplicateQuery(Guid.NewGuid(), "192.168.1.100", "aa:bb:cc:dd:ee:ff"),
CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data!.IsDuplicate.ShouldBeFalse();
}
[Fact]
public async Task Check_duplicate_should_return_duplicate()
{
var service = Substitute.For<ICameraDiscoveryService>();
var response = new CameraCheckResponse(true, Guid.NewGuid(), "Existing Cam",
"192.168.1.100", "aa:bb:cc:dd:ee:ff", "Online");
service.CheckDuplicateAsync(Arg.Any<CheckDuplicateRequest>(), Arg.Any<CancellationToken>())
.Returns(ServiceResult<CameraCheckResponse>.Success(response));
var handler = new CheckDuplicateQueryHandler(service);
var result = await handler.Handle(
new CheckDuplicateQuery(Guid.NewGuid(), "192.168.1.100", "aa:bb:cc:dd:ee:ff"),
CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data!.IsDuplicate.ShouldBeTrue();
result.Data.ExistingName.ShouldBe("Existing Cam");
}
}
@@ -0,0 +1,53 @@
using Heimdall.Application.Discovery.Commands.ConfirmDiscovery;
using Heimdall.Application.Common;
using Heimdall.Application.Common.Persistence;
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using Heimdall.Domain.Enums;
using NSubstitute;
namespace Heimdall.Application.Tests.Handlers.Discovery;
public class ConfirmDiscoveryHandlerTests
{
[Fact]
public async Task Confirm_discovery_should_return_camera()
{
var service = Substitute.For<ICameraDiscoveryService>();
var cameraResponse = new CameraResponse(Guid.NewGuid(), Guid.NewGuid(), null, "Cam1",
"Hikvision", "DS-2CD", "rtsp://...", null, CameraStatus.Online,
CameraDiscoveryMethod.OnvifWsDiscovery, DetectedCameraType.Standard,
CameraCapability.None, "192.168.1.100", "aa:bb:cc:dd:ee:ff",
554, 80, 3702, "H264", 1920, 1080, 50, DateTime.UtcNow, DateTime.UtcNow,
true, true, true, DateTime.UtcNow);
service.ConfirmDiscoveryAsync(Arg.Any<ConfirmDiscoveryRequest>(), Arg.Any<CancellationToken>())
.Returns(ServiceResult<CameraResponse>.Success(cameraResponse));
var handler = new ConfirmDiscoveryCommandHandler(service);
var result = await handler.Handle(
new ConfirmDiscoveryCommand(Guid.NewGuid(), "Cam1", Guid.NewGuid(),
"rtsp://...", null, "admin", "pass", null),
CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
result.Data.Name.ShouldBe("Cam1");
}
[Fact]
public async Task Confirm_discovery_when_service_fails_should_return_failure()
{
var service = Substitute.For<ICameraDiscoveryService>();
service.ConfirmDiscoveryAsync(Arg.Any<ConfirmDiscoveryRequest>(), Arg.Any<CancellationToken>())
.Returns(ServiceResult<CameraResponse>.Failure("Duplicate camera", 409));
var handler = new ConfirmDiscoveryCommandHandler(service);
var result = await handler.Handle(
new ConfirmDiscoveryCommand(Guid.NewGuid(), "Cam1", Guid.NewGuid(),
"rtsp://...", null, null, null, null),
CancellationToken.None);
result.IsSuccess.ShouldBeFalse();
result.StatusCode.ShouldBe(409);
}
}
@@ -0,0 +1,55 @@
using Heimdall.Application.Discovery.Queries.GetScreenshot;
using Heimdall.Application.Common;
using Heimdall.Application.Services;
using NSubstitute;
namespace Heimdall.Application.Tests.Handlers.Discovery;
public class GetScreenshotHandlerTests
{
[Fact]
public async Task Get_screenshot_should_return_bytes()
{
var service = Substitute.For<ICameraDiscoveryService>();
service.GetScreenshotAsync(Arg.Any<Guid>(), 0, Arg.Any<CancellationToken>())
.Returns([0x89, 0x50, 0x4E, 0x47]);
var handler = new GetScreenshotQueryHandler(service);
var result = await handler.Handle(
new GetScreenshotQuery(Guid.NewGuid(), 0), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
result.Data.Length.ShouldBe(4);
}
[Fact]
public async Task Get_screenshot_not_found_should_return_not_found()
{
var service = Substitute.For<ICameraDiscoveryService>();
service.GetScreenshotAsync(Arg.Any<Guid>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns((byte[]?)null);
var handler = new GetScreenshotQueryHandler(service);
var result = await handler.Handle(
new GetScreenshotQuery(Guid.NewGuid(), 0), CancellationToken.None);
result.IsSuccess.ShouldBeFalse();
result.StatusCode.ShouldBe(404);
}
[Fact]
public async Task Get_screenshot_empty_array_should_return_not_found()
{
var service = Substitute.For<ICameraDiscoveryService>();
service.GetScreenshotAsync(Arg.Any<Guid>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns([]);
var handler = new GetScreenshotQueryHandler(service);
var result = await handler.Handle(
new GetScreenshotQuery(Guid.NewGuid(), 1), CancellationToken.None);
result.IsSuccess.ShouldBeFalse();
result.StatusCode.ShouldBe(404);
}
}
@@ -0,0 +1,45 @@
using Heimdall.Application.Discovery.Queries.GetTestSession;
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using NSubstitute;
namespace Heimdall.Application.Tests.Handlers.Discovery;
public class GetTestSessionHandlerTests
{
[Fact]
public async Task Get_test_session_should_return_session()
{
var service = Substitute.For<ICameraDiscoveryService>();
var session = new StreamTestSession(Guid.NewGuid(), "running", 5, 2, 1, []);
service.GetTestSessionAsync(session.SessionId, Arg.Any<CancellationToken>())
.Returns(ServiceResult<StreamTestSession>.Success(session));
var handler = new GetTestSessionQueryHandler(service);
var result = await handler.Handle(
new GetTestSessionQuery(session.SessionId), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
result.Data.Status.ShouldBe("running");
}
[Fact]
public async Task Get_completed_session_should_show_done()
{
var service = Substitute.For<ICameraDiscoveryService>();
var session = new StreamTestSession(Guid.NewGuid(), "done", 2, 2, 2,
[new StreamTestResult("rtsp://cam/stream", ["H264"], 1920, 1080, 30, "shot.jpg", true)]);
service.GetTestSessionAsync(session.SessionId, Arg.Any<CancellationToken>())
.Returns(ServiceResult<StreamTestSession>.Success(session));
var handler = new GetTestSessionQueryHandler(service);
var result = await handler.Handle(
new GetTestSessionQuery(session.SessionId), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data!.Status.ShouldBe("done");
result.Data.Alive.ShouldBe(2);
}
}
@@ -0,0 +1,47 @@
using Heimdall.Application.Discovery.Commands.ProbeIp;
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using Heimdall.Domain.Enums;
using NSubstitute;
namespace Heimdall.Application.Tests.Handlers.Discovery;
public class ProbeIpHandlerTests
{
[Fact]
public async Task Probe_ip_should_return_result()
{
var service = Substitute.For<ICameraDiscoveryService>();
var response = new ProbeResponse("192.168.1.100", true, DetectedCameraType.Standard,
CameraDiscoveryMethod.OnvifWsDiscovery, null, [80, 554], null, null, null, null);
service.ProbeIpAsync(Arg.Any<ProbeRequest>(), Arg.Any<CancellationToken>())
.Returns(ServiceResult<ProbeResponse>.Success(response));
var handler = new ProbeIpCommandHandler(service);
var result = await handler.Handle(
new ProbeIpCommand(Guid.NewGuid(), "192.168.1.100"), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
result.Data.Ip.ShouldBe("192.168.1.100");
result.Data.IsReachable.ShouldBeTrue();
}
[Fact]
public async Task Probe_unreachable_ip_should_return_not_reachable()
{
var service = Substitute.For<ICameraDiscoveryService>();
var response = new ProbeResponse("192.168.1.200", false, DetectedCameraType.Unknown,
CameraDiscoveryMethod.Manual, null, [], null, null, null, null);
service.ProbeIpAsync(Arg.Any<ProbeRequest>(), Arg.Any<CancellationToken>())
.Returns(ServiceResult<ProbeResponse>.Success(response));
var handler = new ProbeIpCommandHandler(service);
var result = await handler.Handle(
new ProbeIpCommand(Guid.NewGuid(), "192.168.1.200"), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data!.IsReachable.ShouldBeFalse();
}
}
@@ -0,0 +1,46 @@
using Heimdall.Application.Discovery.Commands.ScanSubnet;
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using Heimdall.Domain.Enums;
using NSubstitute;
namespace Heimdall.Application.Tests.Handlers.Discovery;
public class ScanSubnetHandlerTests
{
[Fact]
public async Task Scan_subnet_should_return_results()
{
var service = Substitute.For<ICameraDiscoveryService>();
var probe1 = new ProbeResponse("192.168.1.10", true, DetectedCameraType.Standard,
CameraDiscoveryMethod.OnvifWsDiscovery, null, [80], null, null, null, ["Hikvision"]);
var probe2 = new ProbeResponse("192.168.1.20", true, DetectedCameraType.Unknown,
CameraDiscoveryMethod.HttpProbe, null, [80, 8080], null, null, null, null);
service.ScanSubnetAsync(Arg.Any<ScanRequest>(), Arg.Any<CancellationToken>(), null)
.Returns(ServiceResult<IReadOnlyList<ProbeResponse>>.Success(new List<ProbeResponse> { probe1, probe2 }));
var handler = new ScanSubnetCommandHandler(service);
var result = await handler.Handle(
new ScanSubnetCommand(Guid.NewGuid(), "192.168.1.0/24"), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
result.Data.Count.ShouldBe(2);
}
[Fact]
public async Task Scan_subnet_empty_should_return_empty()
{
var service = Substitute.For<ICameraDiscoveryService>();
service.ScanSubnetAsync(Arg.Any<ScanRequest>(), Arg.Any<CancellationToken>(), null)
.Returns(ServiceResult<IReadOnlyList<ProbeResponse>>.Success(new List<ProbeResponse>()));
var handler = new ScanSubnetCommandHandler(service);
var result = await handler.Handle(
new ScanSubnetCommand(Guid.NewGuid(), "10.0.0.0/24"), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldBeEmpty();
}
}
@@ -0,0 +1,46 @@
using Heimdall.Application.Discovery.Queries.SearchDatabase;
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using NSubstitute;
namespace Heimdall.Application.Tests.Handlers.Discovery;
public class SearchDatabaseHandlerTests
{
[Fact]
public async Task Search_database_should_return_results()
{
var service = Substitute.For<ICameraDiscoveryService>();
var response = new SearchResponse([
new CameraDbEntry("brand", "b:hikvision", "Hikvision"),
new CameraDbEntry("model", "m:hikvision:DS-2CD", "DS-2CD"),
]);
service.SearchDatabaseAsync("hikvision", Arg.Any<CancellationToken>())
.Returns(ServiceResult<SearchResponse>.Success(response));
var handler = new SearchDatabaseQueryHandler(service);
var result = await handler.Handle(
new SearchDatabaseQuery("hikvision"), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
result.Data.Results.Length.ShouldBe(2);
}
[Fact]
public async Task Search_database_empty_should_return_empty()
{
var service = Substitute.For<ICameraDiscoveryService>();
var response = new SearchResponse([]);
service.SearchDatabaseAsync("nonexistent", Arg.Any<CancellationToken>())
.Returns(ServiceResult<SearchResponse>.Success(response));
var handler = new SearchDatabaseQueryHandler(service);
var result = await handler.Handle(
new SearchDatabaseQuery("nonexistent"), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data!.Results.ShouldBeEmpty();
}
}
@@ -0,0 +1,46 @@
using Heimdall.Application.Discovery.Commands.TestStreams;
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using NSubstitute;
namespace Heimdall.Application.Tests.Handlers.Discovery;
public class TestStreamsHandlerTests
{
[Fact]
public async Task Test_streams_should_return_session()
{
var service = Substitute.For<ICameraDiscoveryService>();
var session = new StreamTestSession(Guid.NewGuid(), "running", 3, 1, 0, []);
service.TestStreamsAsync(Arg.Any<StreamTestRequest>(), Arg.Any<CancellationToken>())
.Returns(ServiceResult<StreamTestSession>.Success(session));
var handler = new TestStreamsCommandHandler(service);
var result = await handler.Handle(
new TestStreamsCommand("src-1", ["rtsp://cam1/stream1", "rtsp://cam1/stream2"]),
CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
result.Data.Status.ShouldBe("running");
}
[Fact]
public async Task Test_streams_with_single_url_should_work()
{
var service = Substitute.For<ICameraDiscoveryService>();
var session = new StreamTestSession(Guid.NewGuid(), "done", 1, 1, 1,
[new StreamTestResult("rtsp://cam1/stream1", ["H264"], 1920, 1080, 50, "shot.jpg", true)]);
service.TestStreamsAsync(Arg.Any<StreamTestRequest>(), Arg.Any<CancellationToken>())
.Returns(ServiceResult<StreamTestSession>.Success(session));
var handler = new TestStreamsCommandHandler(service);
var result = await handler.Handle(
new TestStreamsCommand("src-1", ["rtsp://cam1/stream1"]), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data!.Tested.ShouldBe(1);
result.Data.Alive.ShouldBe(1);
}
}
@@ -0,0 +1,85 @@
using Heimdall.Application.Common;
using Heimdall.Application.Groups.Commands.AddUserToGroup;
using Heimdall.Application.Tests.Common;
using Heimdall.Domain.Entities;
using NSubstitute;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Tests.Handlers.Groups;
public class AddUserToGroupHandlerTests
{
private readonly Group _group = new("Test Group", "Description");
private readonly AppUser _user = new()
{
Id = Guid.NewGuid(),
UserName = "user@test.com",
Email = "user@test.com"
};
[Fact]
public async Task Add_user_to_group_should_return_success()
{
var context = Substitute.For<IApplicationDbContext>();
context.Groups.Returns(MockDbSetHelper.CreateFor<Group>([_group]));
context.Users.Returns(MockDbSetHelper.CreateFor<AppUser>([_user]));
context.UserGroups.Returns(MockDbSetHelper.CreateFor<UserGroup>());
context.AuditLogs.Returns(MockDbSetHelper.CreateFor<AuditLog>());
var handler = new AddUserToGroupCommandHandler(context);
var result = await handler.Handle(
new AddUserToGroupCommand(_group.Id, _user.Id), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
await context.Received(1).SaveChangesWithRetryAsync(Arg.Any<int>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task Add_user_to_nonexistent_group_should_return_not_found()
{
var context = Substitute.For<IApplicationDbContext>();
context.Groups.Returns(MockDbSetHelper.CreateFor<Group>([_group]));
context.Users.Returns(MockDbSetHelper.CreateFor<AppUser>([_user]));
context.UserGroups.Returns(MockDbSetHelper.CreateFor<UserGroup>());
var handler = new AddUserToGroupCommandHandler(context);
var result = await handler.Handle(
new AddUserToGroupCommand(Guid.NewGuid(), _user.Id), CancellationToken.None);
result.IsSuccess.ShouldBeFalse();
result.StatusCode.ShouldBe(404);
}
[Fact]
public async Task Add_nonexistent_user_to_group_should_return_not_found()
{
var context = Substitute.For<IApplicationDbContext>();
context.Groups.Returns(MockDbSetHelper.CreateFor<Group>([_group]));
context.Users.Returns(MockDbSetHelper.CreateFor<AppUser>());
context.UserGroups.Returns(MockDbSetHelper.CreateFor<UserGroup>());
var handler = new AddUserToGroupCommandHandler(context);
var result = await handler.Handle(
new AddUserToGroupCommand(_group.Id, Guid.NewGuid()), CancellationToken.None);
result.IsSuccess.ShouldBeFalse();
result.StatusCode.ShouldBe(404);
}
[Fact]
public async Task Add_existing_member_should_return_conflict()
{
var existingMembership = new UserGroup(_user.Id, _group.Id);
var context = Substitute.For<IApplicationDbContext>();
context.Groups.Returns(MockDbSetHelper.CreateFor<Group>([_group]));
context.Users.Returns(MockDbSetHelper.CreateFor<AppUser>([_user]));
context.UserGroups.Returns(MockDbSetHelper.CreateFor<UserGroup>([existingMembership]));
var handler = new AddUserToGroupCommandHandler(context);
var result = await handler.Handle(
new AddUserToGroupCommand(_group.Id, _user.Id), CancellationToken.None);
result.IsSuccess.ShouldBeFalse();
result.StatusCode.ShouldBe(409);
}
}
@@ -0,0 +1,43 @@
using Heimdall.Application.Common;
using Heimdall.Application.Groups.Commands.CreateGroup;
using Heimdall.Application.Tests.Common;
using Heimdall.Domain.Entities;
using NSubstitute;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Tests.Handlers.Groups;
public class CreateGroupHandlerTests
{
[Fact]
public async Task Create_group_should_return_success()
{
var context = Substitute.For<IApplicationDbContext>();
context.Groups.Returns(MockDbSetHelper.CreateFor<Group>());
context.AuditLogs.Returns(MockDbSetHelper.CreateFor<AuditLog>());
var handler = new CreateGroupCommandHandler(context);
var result = await handler.Handle(
new CreateGroupCommand("New Group", "A test group"), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
result.Data.Name.ShouldBe("New Group");
await context.Received(1).SaveChangesWithRetryAsync(Arg.Any<int>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task Create_duplicate_group_name_should_return_conflict()
{
var existingGroup = new Group("Existing Group", null);
var context = Substitute.For<IApplicationDbContext>();
context.Groups.Returns(MockDbSetHelper.CreateFor<Group>([existingGroup]));
var handler = new CreateGroupCommandHandler(context);
var result = await handler.Handle(
new CreateGroupCommand("Existing Group", null), CancellationToken.None);
result.IsSuccess.ShouldBeFalse();
result.StatusCode.ShouldBe(409);
}
}
@@ -0,0 +1,40 @@
using Heimdall.Application.Common;
using Heimdall.Application.Groups.Commands.DeleteGroup;
using Heimdall.Application.Tests.Common;
using Heimdall.Domain.Entities;
using NSubstitute;
namespace Heimdall.Application.Tests.Handlers.Groups;
public class DeleteGroupHandlerTests
{
[Fact]
public async Task Delete_group_should_return_success()
{
var group = new Group("Test Group", "Description");
var context = Substitute.For<IApplicationDbContext>();
context.Groups.Returns(MockDbSetHelper.CreateFor<Group>([group]));
context.AuditLogs.Returns(MockDbSetHelper.CreateFor<AuditLog>());
var handler = new DeleteGroupCommandHandler(context);
var result = await handler.Handle(new DeleteGroupCommand(group.Id), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
group.IsDeleted.ShouldBeTrue();
group.DeletedAt.ShouldNotBeNull();
await context.Received(1).SaveChangesWithRetryAsync(Arg.Any<int>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task Delete_nonexistent_group_should_return_not_found()
{
var context = Substitute.For<IApplicationDbContext>();
context.Groups.Returns(MockDbSetHelper.CreateFor<Group>([new Group("Test", null)]));
var handler = new DeleteGroupCommandHandler(context);
var result = await handler.Handle(new DeleteGroupCommand(Guid.NewGuid()), CancellationToken.None);
result.IsSuccess.ShouldBeFalse();
result.StatusCode.ShouldBe(404);
}
}
@@ -0,0 +1,40 @@
using Heimdall.Application.Common;
using Heimdall.Application.Groups.Queries.GetGroup;
using Heimdall.Application.Tests.Common;
using Heimdall.Domain.Entities;
using NSubstitute;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Tests.Handlers.Groups;
public class GetGroupHandlerTests
{
[Fact]
public async Task Get_group_should_return_group()
{
var group = new Group("Test Group", "Description");
var context = Substitute.For<IApplicationDbContext>();
context.Groups.Returns(MockDbSetHelper.CreateFor<Group>([group]));
context.UserGroups.Returns(MockDbSetHelper.CreateFor<UserGroup>());
var handler = new GetGroupQueryHandler(context);
var result = await handler.Handle(new GetGroupQuery(group.Id), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
result.Data.Name.ShouldBe("Test Group");
}
[Fact]
public async Task Get_nonexistent_group_should_return_not_found()
{
var context = Substitute.For<IApplicationDbContext>();
context.Groups.Returns(MockDbSetHelper.CreateFor<Group>([new Group("Test", null)]));
var handler = new GetGroupQueryHandler(context);
var result = await handler.Handle(new GetGroupQuery(Guid.NewGuid()), CancellationToken.None);
result.IsSuccess.ShouldBeFalse();
result.StatusCode.ShouldBe(404);
}
}
@@ -0,0 +1,66 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Application.Groups.Queries.GetGroupMembers;
using Heimdall.Application.Tests.Common;
using Heimdall.Domain.Entities;
using NSubstitute;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Tests.Handlers.Groups;
public class GetGroupMembersHandlerTests
{
[Fact]
public async Task Get_group_members_should_return_members()
{
var group = new Group("Test Group", null);
var userId1 = Guid.NewGuid();
var userId2 = Guid.NewGuid();
var userGroup1 = new UserGroup(userId1, group.Id);
var userGroup2 = new UserGroup(userId2, group.Id);
var user1 = new AppUser { Id = userId1, UserName = "a@test.com", Email = "a@test.com", DisplayName = "User A" };
var user2 = new AppUser { Id = userId2, UserName = "b@test.com", Email = "b@test.com", DisplayName = "User B" };
var context = Substitute.For<IApplicationDbContext>();
context.Groups.Returns(MockDbSetHelper.CreateFor<Group>([group]));
context.UserGroups.Returns(MockDbSetHelper.CreateFor<UserGroup>([userGroup1, userGroup2]));
context.Users.Returns(MockDbSetHelper.CreateFor<AppUser>([user1, user2]));
var handler = new GetGroupMembersQueryHandler(context);
var result = await handler.Handle(new GetGroupMembersQuery(group.Id), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
result.Data.Count.ShouldBe(2);
}
[Fact]
public async Task Get_group_members_nonexistent_group_should_return_not_found()
{
var context = Substitute.For<IApplicationDbContext>();
context.Groups.Returns(MockDbSetHelper.CreateFor<Group>());
var handler = new GetGroupMembersQueryHandler(context);
var result = await handler.Handle(new GetGroupMembersQuery(Guid.NewGuid()), CancellationToken.None);
result.IsSuccess.ShouldBeFalse();
result.StatusCode.ShouldBe(404);
}
[Fact]
public async Task Get_group_members_empty_should_return_empty_list()
{
var group = new Group("Empty Group", null);
var context = Substitute.For<IApplicationDbContext>();
context.Groups.Returns(MockDbSetHelper.CreateFor<Group>([group]));
context.UserGroups.Returns(MockDbSetHelper.CreateFor<UserGroup>());
context.Users.Returns(MockDbSetHelper.CreateFor<AppUser>());
var handler = new GetGroupMembersQueryHandler(context);
var result = await handler.Handle(new GetGroupMembersQuery(group.Id), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldBeEmpty();
}
}
@@ -0,0 +1,64 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Application.Groups.Queries.GetGroups;
using Heimdall.Application.Tests.Common;
using Heimdall.Domain.Entities;
using NSubstitute;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Tests.Handlers.Groups;
public class GetGroupsHandlerTests
{
private readonly List<Group> _groups =
[
new Group("Beta", null),
new Group("Alpha", null),
new Group("Gamma", null),
];
[Fact]
public async Task Get_groups_should_return_paginated_results()
{
var context = Substitute.For<IApplicationDbContext>();
context.Groups.Returns(MockDbSetHelper.CreateFor<Group>(_groups));
context.UserGroups.Returns(MockDbSetHelper.CreateFor<UserGroup>());
var handler = new GetGroupsQueryHandler(context);
var result = await handler.Handle(new GetGroupsQuery(1, 10), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
result.Data.Items.Count.ShouldBe(3);
result.Data.TotalCount.ShouldBe(3);
}
[Fact]
public async Task Get_groups_empty_result_should_return_empty_list()
{
var context = Substitute.For<IApplicationDbContext>();
context.Groups.Returns(MockDbSetHelper.CreateFor<Group>());
context.UserGroups.Returns(MockDbSetHelper.CreateFor<UserGroup>());
var handler = new GetGroupsQueryHandler(context);
var result = await handler.Handle(new GetGroupsQuery(1, 10), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data!.Items.ShouldBeEmpty();
}
[Fact]
public async Task Get_groups_should_respect_pagination()
{
var context = Substitute.For<IApplicationDbContext>();
context.Groups.Returns(MockDbSetHelper.CreateFor<Group>(_groups));
context.UserGroups.Returns(MockDbSetHelper.CreateFor<UserGroup>());
var handler = new GetGroupsQueryHandler(context);
var result = await handler.Handle(new GetGroupsQuery(1, 2), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data!.Items.Count.ShouldBe(2);
result.Data.TotalCount.ShouldBe(3);
}
}
@@ -0,0 +1,42 @@
using Heimdall.Application.Common;
using Heimdall.Application.Groups.Commands.RemoveUserFromGroup;
using Heimdall.Application.Tests.Common;
using Heimdall.Domain.Entities;
using NSubstitute;
namespace Heimdall.Application.Tests.Handlers.Groups;
public class RemoveUserFromGroupHandlerTests
{
[Fact]
public async Task Remove_user_from_group_should_return_success()
{
var userId = Guid.NewGuid();
var groupId = Guid.NewGuid();
var userGroup = new UserGroup(userId, groupId);
var context = Substitute.For<IApplicationDbContext>();
context.UserGroups.Returns(MockDbSetHelper.CreateFor<UserGroup>([userGroup]));
context.AuditLogs.Returns(MockDbSetHelper.CreateFor<AuditLog>());
var handler = new RemoveUserFromGroupCommandHandler(context);
var result = await handler.Handle(
new RemoveUserFromGroupCommand(groupId, userId), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
await context.Received(1).SaveChangesWithRetryAsync(Arg.Any<int>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task Remove_nonexistent_member_should_return_not_found()
{
var context = Substitute.For<IApplicationDbContext>();
context.UserGroups.Returns(MockDbSetHelper.CreateFor<UserGroup>());
var handler = new RemoveUserFromGroupCommandHandler(context);
var result = await handler.Handle(
new RemoveUserFromGroupCommand(Guid.NewGuid(), Guid.NewGuid()), CancellationToken.None);
result.IsSuccess.ShouldBeFalse();
result.StatusCode.ShouldBe(404);
}
}
@@ -0,0 +1,45 @@
using Heimdall.Application.Common;
using Heimdall.Application.Groups.Commands.UpdateGroup;
using Heimdall.Application.Tests.Common;
using Heimdall.Domain.Entities;
using NSubstitute;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Tests.Handlers.Groups;
public class UpdateGroupHandlerTests
{
private readonly Group _group = new("Original Name", "Original description");
[Fact]
public async Task Update_group_should_return_success()
{
var context = Substitute.For<IApplicationDbContext>();
context.Groups.Returns(MockDbSetHelper.CreateFor<Group>([_group]));
context.AuditLogs.Returns(MockDbSetHelper.CreateFor<AuditLog>());
context.UserGroups.Returns(MockDbSetHelper.CreateFor<UserGroup>());
var handler = new UpdateGroupCommandHandler(context);
var result = await handler.Handle(
new UpdateGroupCommand(_group.Id, "Updated Name", "Updated description"), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
result.Data.Name.ShouldBe("Updated Name");
await context.Received(1).SaveChangesWithRetryAsync(Arg.Any<int>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task Update_nonexistent_group_should_return_not_found()
{
var context = Substitute.For<IApplicationDbContext>();
context.Groups.Returns(MockDbSetHelper.CreateFor<Group>([_group]));
var handler = new UpdateGroupCommandHandler(context);
var result = await handler.Handle(
new UpdateGroupCommand(Guid.NewGuid(), "Name", null), CancellationToken.None);
result.IsSuccess.ShouldBeFalse();
result.StatusCode.ShouldBe(404);
}
}
@@ -0,0 +1,41 @@
using Heimdall.Application.Common;
using Heimdall.Application.Persons.Commands.CreatePerson;
using Heimdall.Application.Tests.Common;
using Heimdall.Domain.Entities;
using NSubstitute;
namespace Heimdall.Application.Tests.Handlers.Persons;
public class CreatePersonHandlerTests
{
[Fact]
public async Task Create_person_should_return_success()
{
var context = Substitute.For<IApplicationDbContext>();
context.Persons.Returns(MockDbSetHelper.CreateFor<Person>());
var handler = new CreatePersonCommandHandler(context);
var result = await handler.Handle(
new CreatePersonCommand("New Person", "family", null, false), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
result.Data.DisplayName.ShouldBe("New Person");
result.Data.Category.ShouldBe("family");
await context.Received(1).SaveChangesWithRetryAsync(Arg.Any<int>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task Create_person_default_category_should_be_null()
{
var context = Substitute.For<IApplicationDbContext>();
context.Persons.Returns(MockDbSetHelper.CreateFor<Person>());
var handler = new CreatePersonCommandHandler(context);
var result = await handler.Handle(
new CreatePersonCommand("Minimal Person", null, null), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data!.DisplayName.ShouldBe("Minimal Person");
}
}
@@ -0,0 +1,37 @@
using Heimdall.Application.Common;
using Heimdall.Application.Persons.Commands.DeleteFace;
using Heimdall.Application.Tests.Common;
using Heimdall.Domain.Entities;
using NSubstitute;
namespace Heimdall.Application.Tests.Handlers.Persons;
public class DeleteFaceHandlerTests
{
[Fact]
public async Task Delete_face_should_return_success()
{
var face = new KnownFace(Guid.NewGuid(), [0.1f], "thumb.jpg", null);
var context = Substitute.For<IApplicationDbContext>();
context.KnownFaces.Returns(MockDbSetHelper.CreateFor<KnownFace>([face]));
var handler = new DeleteFaceCommandHandler(context);
var result = await handler.Handle(new DeleteFaceCommand(face.Id), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
await context.Received(1).SaveChangesWithRetryAsync(Arg.Any<int>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task Delete_nonexistent_face_should_return_not_found()
{
var context = Substitute.For<IApplicationDbContext>();
context.KnownFaces.Returns(MockDbSetHelper.CreateFor<KnownFace>());
var handler = new DeleteFaceCommandHandler(context);
var result = await handler.Handle(new DeleteFaceCommand(Guid.NewGuid()), CancellationToken.None);
result.IsSuccess.ShouldBeFalse();
result.StatusCode.ShouldBe(404);
}
}
@@ -0,0 +1,37 @@
using Heimdall.Application.Common;
using Heimdall.Application.Persons.Commands.DeletePerson;
using Heimdall.Application.Tests.Common;
using Heimdall.Domain.Entities;
using NSubstitute;
namespace Heimdall.Application.Tests.Handlers.Persons;
public class DeletePersonHandlerTests
{
[Fact]
public async Task Delete_person_should_return_success()
{
var person = new Person("Test Person");
var context = Substitute.For<IApplicationDbContext>();
context.Persons.Returns(MockDbSetHelper.CreateFor<Person>([person]));
var handler = new DeletePersonCommandHandler(context);
var result = await handler.Handle(new DeletePersonCommand(person.Id), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
await context.Received(1).SaveChangesWithRetryAsync(Arg.Any<int>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task Delete_nonexistent_person_should_return_not_found()
{
var context = Substitute.For<IApplicationDbContext>();
context.Persons.Returns(MockDbSetHelper.CreateFor<Person>());
var handler = new DeletePersonCommandHandler(context);
var result = await handler.Handle(new DeletePersonCommand(Guid.NewGuid()), CancellationToken.None);
result.IsSuccess.ShouldBeFalse();
result.StatusCode.ShouldBe(404);
}
}
@@ -0,0 +1,44 @@
using Heimdall.Application.Common;
using Heimdall.Application.Persons.Queries.GetFaces;
using Heimdall.Application.Tests.Common;
using Heimdall.Domain.Entities;
using NSubstitute;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Tests.Handlers.Persons;
public class GetFacesHandlerTests
{
[Fact]
public async Task Get_faces_should_return_faces()
{
var personId = Guid.NewGuid();
var faces = new List<KnownFace>
{
new(personId, [0.1f], "thumb1.jpg", "evt-1"),
new(personId, [0.2f], "thumb2.jpg", "evt-2"),
};
var context = Substitute.For<IApplicationDbContext>();
context.KnownFaces.Returns(MockDbSetHelper.CreateFor<KnownFace>(faces));
var handler = new GetFacesQueryHandler(context);
var result = await handler.Handle(new GetFacesQuery(personId), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
result.Data.Count.ShouldBe(2);
}
[Fact]
public async Task Get_faces_empty_should_return_empty_list()
{
var context = Substitute.For<IApplicationDbContext>();
context.KnownFaces.Returns(MockDbSetHelper.CreateFor<KnownFace>());
var handler = new GetFacesQueryHandler(context);
var result = await handler.Handle(new GetFacesQuery(Guid.NewGuid()), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldBeEmpty();
}
}
@@ -0,0 +1,40 @@
using Heimdall.Application.Common;
using Heimdall.Application.Persons.Queries.GetPerson;
using Heimdall.Application.Tests.Common;
using Heimdall.Domain.Entities;
using NSubstitute;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Tests.Handlers.Persons;
public class GetPersonHandlerTests
{
[Fact]
public async Task Get_person_should_return_person()
{
var person = new Person("Test Person", "family");
var context = Substitute.For<IApplicationDbContext>();
context.Persons.Returns(MockDbSetHelper.CreateFor<Person>([person]));
var handler = new GetPersonQueryHandler(context);
var result = await handler.Handle(new GetPersonQuery(person.Id), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
result.Data.DisplayName.ShouldBe("Test Person");
result.Data.Category.ShouldBe("family");
}
[Fact]
public async Task Get_nonexistent_person_should_return_not_found()
{
var context = Substitute.For<IApplicationDbContext>();
context.Persons.Returns(MockDbSetHelper.CreateFor<Person>());
var handler = new GetPersonQueryHandler(context);
var result = await handler.Handle(new GetPersonQuery(Guid.NewGuid()), CancellationToken.None);
result.IsSuccess.ShouldBeFalse();
result.StatusCode.ShouldBe(404);
}
}
@@ -0,0 +1,64 @@
using Heimdall.Application.Common;
using Heimdall.Application.Persons.Queries.GetPersons;
using Heimdall.Application.Tests.Common;
using Heimdall.Domain.Entities;
using NSubstitute;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Tests.Handlers.Persons;
public class GetPersonsHandlerTests
{
[Fact]
public async Task Get_persons_should_return_all()
{
var persons = new List<Person>
{
new("Charlie", "family"),
new("Alice", "employee"),
new("Bob", "family"),
};
var context = Substitute.For<IApplicationDbContext>();
context.Persons.Returns(MockDbSetHelper.CreateFor<Person>(persons));
var handler = new GetPersonsQueryHandler(context);
var result = await handler.Handle(new GetPersonsQuery(null), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
result.Data.Count.ShouldBe(3);
}
[Fact]
public async Task Get_persons_should_filter_by_category()
{
var persons = new List<Person>
{
new("Charlie", "family"),
new("Alice", "employee"),
new("Bob", "family"),
};
var context = Substitute.For<IApplicationDbContext>();
context.Persons.Returns(MockDbSetHelper.CreateFor<Person>(persons));
var handler = new GetPersonsQueryHandler(context);
var result = await handler.Handle(new GetPersonsQuery("family"), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
result.Data.Count.ShouldBe(2);
}
[Fact]
public async Task Get_persons_empty_should_return_empty_list()
{
var context = Substitute.For<IApplicationDbContext>();
context.Persons.Returns(MockDbSetHelper.CreateFor<Person>());
var handler = new GetPersonsQueryHandler(context);
var result = await handler.Handle(new GetPersonsQuery(null), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldBeEmpty();
}
}
@@ -0,0 +1,44 @@
using Heimdall.Application.Common;
using Heimdall.Application.Persons.Commands.RegisterFace;
using Heimdall.Application.Tests.Common;
using Heimdall.Domain.Entities;
using NSubstitute;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Tests.Handlers.Persons;
public class RegisterFaceHandlerTests
{
[Fact]
public async Task Register_face_should_return_success()
{
var person = new Person("Test Person");
var context = Substitute.For<IApplicationDbContext>();
context.Persons.Returns(MockDbSetHelper.CreateFor<Person>([person]));
var handler = new RegisterFaceCommandHandler(context);
var embedding = new float[] { 0.1f, 0.2f, 0.3f };
var result = await handler.Handle(
new RegisterFaceCommand(person.Id, embedding, "thumb.jpg", "evt-1"), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
result.Data.PersonId.ShouldBe(person.Id);
person.Faces.Count.ShouldBe(1);
await context.Received(1).SaveChangesWithRetryAsync(Arg.Any<int>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task Register_face_nonexistent_person_should_return_not_found()
{
var context = Substitute.For<IApplicationDbContext>();
context.Persons.Returns(MockDbSetHelper.CreateFor<Person>());
var handler = new RegisterFaceCommandHandler(context);
var result = await handler.Handle(
new RegisterFaceCommand(Guid.NewGuid(), [0.1f], null, null), CancellationToken.None);
result.IsSuccess.ShouldBeFalse();
result.StatusCode.ShouldBe(404);
}
}
@@ -0,0 +1,44 @@
using Heimdall.Application.Common;
using Heimdall.Application.Persons.Commands.UpdatePerson;
using Heimdall.Application.Tests.Common;
using Heimdall.Domain.Entities;
using NSubstitute;
namespace Heimdall.Application.Tests.Handlers.Persons;
public class UpdatePersonHandlerTests
{
[Fact]
public async Task Update_person_should_return_success()
{
var person = new Person("Old Name", "family");
var context = Substitute.For<IApplicationDbContext>();
context.Persons.Returns(MockDbSetHelper.CreateFor<Person>([person]));
var handler = new UpdatePersonCommandHandler(context);
var result = await handler.Handle(
new UpdatePersonCommand(person.Id, "New Name", "Some notes", "employee", true),
CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
result.Data.DisplayName.ShouldBe("New Name");
result.Data.IsWatchlisted.ShouldBeTrue();
await context.Received(1).SaveChangesWithRetryAsync(Arg.Any<int>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task Update_nonexistent_person_should_return_not_found()
{
var context = Substitute.For<IApplicationDbContext>();
context.Persons.Returns(MockDbSetHelper.CreateFor<Person>());
var handler = new UpdatePersonCommandHandler(context);
var result = await handler.Handle(
new UpdatePersonCommand(Guid.NewGuid(), "Name", null, null, false),
CancellationToken.None);
result.IsSuccess.ShouldBeFalse();
result.StatusCode.ShouldBe(404);
}
}
@@ -0,0 +1,86 @@
using Heimdall.Application.Common;
using Heimdall.Application.Common.Persistence;
using Heimdall.Application.Users.Commands.AssignRoles;
using Heimdall.Domain.Entities;
using Microsoft.AspNetCore.Identity;
using NSubstitute;
namespace Heimdall.Application.Tests.Handlers.Users;
public class AssignRolesHandlerTests
{
private readonly AppUser _user = new()
{
Id = Guid.NewGuid(),
UserName = "test@test.com",
Email = "test@test.com"
};
private readonly UserManager<AppUser> _userManager;
private readonly IUserRepository _repository;
private readonly AssignRolesHandler _handler;
public AssignRolesHandlerTests()
{
var store = Substitute.For<IUserStore<AppUser>>();
_userManager = Substitute.For<UserManager<AppUser>>(store, null!, null!, null!, null!, null!, null!, null!, null!);
_repository = Substitute.For<IUserRepository>();
_handler = new AssignRolesHandler(_userManager, _repository);
}
[Fact]
public async Task Assign_roles_should_return_success()
{
_userManager.FindByIdAsync(_user.Id.ToString()).Returns(_user);
_userManager.GetRolesAsync(_user).Returns(new List<string> { "Viewer" });
_userManager.RemoveFromRolesAsync(_user, Arg.Any<IEnumerable<string>>()).Returns(IdentityResult.Success);
_userManager.AddToRolesAsync(_user, Arg.Any<IEnumerable<string>>()).Returns(IdentityResult.Success);
var result = await _handler.Handle(
new AssignRolesCommand(_user.Id, new List<string> { "Admin", "Manager" }), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
await _repository.Received(1).AddAuditLogAsync(null, "UserRolesUpdated", "User",
_user.Id.ToString(), "Viewer", "Admin,Manager", Arg.Any<CancellationToken>());
}
[Fact]
public async Task Assign_roles_nonexistent_user_should_return_not_found()
{
_userManager.FindByIdAsync(Arg.Any<string>()).Returns((AppUser?)null);
var result = await _handler.Handle(
new AssignRolesCommand(Guid.NewGuid(), new List<string> { "Admin" }), CancellationToken.None);
result.IsSuccess.ShouldBeFalse();
result.StatusCode.ShouldBe(404);
}
[Fact]
public async Task Remove_last_admin_role_should_return_failure()
{
_userManager.FindByIdAsync(_user.Id.ToString()).Returns(_user);
_userManager.GetRolesAsync(_user).Returns(new List<string> { "Admin" });
_repository.CountAdminUsersAsync(Arg.Any<CancellationToken>()).Returns(1);
var result = await _handler.Handle(
new AssignRolesCommand(_user.Id, new List<string> { "Viewer" }), CancellationToken.None);
result.IsSuccess.ShouldBeFalse();
result.StatusCode.ShouldBe(400);
}
[Fact]
public async Task Assign_roles_should_allow_keeping_admin()
{
_userManager.FindByIdAsync(_user.Id.ToString()).Returns(_user);
_userManager.GetRolesAsync(_user).Returns(new List<string> { "Admin", "Viewer" });
_userManager.RemoveFromRolesAsync(_user, Arg.Any<IEnumerable<string>>()).Returns(IdentityResult.Success);
_userManager.AddToRolesAsync(_user, Arg.Any<IEnumerable<string>>()).Returns(IdentityResult.Success);
var result = await _handler.Handle(
new AssignRolesCommand(_user.Id, new List<string> { "Admin", "Manager" }), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
}
}
@@ -0,0 +1,68 @@
using Heimdall.Application.Common;
using Heimdall.Application.Common.Persistence;
using Heimdall.Application.Users.Commands.AssignSites;
using Heimdall.Domain.Entities;
using Microsoft.AspNetCore.Identity;
using NSubstitute;
namespace Heimdall.Application.Tests.Handlers.Users;
public class AssignSitesHandlerTests
{
private readonly AppUser _user = new()
{
Id = Guid.NewGuid(),
UserName = "test@test.com",
Email = "test@test.com"
};
private readonly UserManager<AppUser> _userManager;
private readonly IUserRepository _repository;
private readonly AssignSitesHandler _handler;
public AssignSitesHandlerTests()
{
var store = Substitute.For<IUserStore<AppUser>>();
_userManager = Substitute.For<UserManager<AppUser>>(store, null!, null!, null!, null!, null!, null!, null!, null!);
_repository = Substitute.For<IUserRepository>();
_handler = new AssignSitesHandler(_userManager, _repository);
}
[Fact]
public async Task Assign_sites_should_return_success()
{
_userManager.FindByIdAsync(_user.Id.ToString()).Returns(_user);
var siteIds = new List<Guid> { Guid.NewGuid(), Guid.NewGuid() };
var result = await _handler.Handle(
new AssignSitesCommand(_user.Id, siteIds), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
await _repository.Received(1).SetUserSitesAsync(_user.Id, siteIds, Arg.Any<CancellationToken>());
}
[Fact]
public async Task Assign_sites_nonexistent_user_should_return_not_found()
{
_userManager.FindByIdAsync(Arg.Any<string>()).Returns((AppUser?)null);
var result = await _handler.Handle(
new AssignSitesCommand(Guid.NewGuid(), new List<Guid>()), CancellationToken.None);
result.IsSuccess.ShouldBeFalse();
result.StatusCode.ShouldBe(404);
}
[Fact]
public async Task Assign_empty_sites_should_return_success()
{
_userManager.FindByIdAsync(_user.Id.ToString()).Returns(_user);
var emptySiteIds = new List<Guid>();
var result = await _handler.Handle(
new AssignSitesCommand(_user.Id, emptySiteIds), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
await _repository.Received(1).SetUserSitesAsync(_user.Id, emptySiteIds, Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,94 @@
using Heimdall.Application.Common;
using Heimdall.Application.Common.Persistence;
using Heimdall.Application.Users.Commands.DeleteUser;
using Heimdall.Domain.Entities;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Logging;
using NSubstitute;
namespace Heimdall.Application.Tests.Handlers.Users;
public class DeleteUserHandlerTests
{
private readonly AppUser _user = new()
{
Id = Guid.NewGuid(),
UserName = "test@test.com",
Email = "test@test.com",
DisplayName = "Test User"
};
private readonly Guid _currentUserId = Guid.NewGuid();
private readonly UserManager<AppUser> _userManager;
private readonly IUserRepository _repository;
private readonly DeleteUserHandler _handler;
public DeleteUserHandlerTests()
{
var store = Substitute.For<IUserStore<AppUser>>();
_userManager = Substitute.For<UserManager<AppUser>>(store, null!, null!, null!, null!, null!, null!, null!, null!);
_repository = Substitute.For<IUserRepository>();
_handler = new DeleteUserHandler(_userManager, _repository);
}
[Fact]
public async Task Delete_user_should_return_success()
{
_userManager.FindByIdAsync(_user.Id.ToString()).Returns(_user);
_userManager.GetRolesAsync(_user).Returns(new List<string> { "Viewer" });
_userManager.DeleteAsync(_user).Returns(IdentityResult.Success);
var result = await _handler.Handle(new DeleteUserCommand(_user.Id, _currentUserId), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
await _repository.Received(1).RemoveUserDataAsync(_user.Id, Arg.Any<CancellationToken>());
await _repository.Received(1).AddAuditLogAsync(_currentUserId, "UserDeleted", "User",
_user.Id.ToString(), null, null, Arg.Any<CancellationToken>());
}
[Fact]
public async Task Delete_own_account_should_return_failure()
{
var result = await _handler.Handle(new DeleteUserCommand(_currentUserId, _currentUserId), CancellationToken.None);
result.IsSuccess.ShouldBeFalse();
result.StatusCode.ShouldBe(400);
}
[Fact]
public async Task Delete_nonexistent_user_should_return_not_found()
{
_userManager.FindByIdAsync(Arg.Any<string>()).Returns((AppUser?)null);
var result = await _handler.Handle(new DeleteUserCommand(Guid.NewGuid(), _currentUserId), CancellationToken.None);
result.IsSuccess.ShouldBeFalse();
result.StatusCode.ShouldBe(404);
}
[Fact]
public async Task Delete_last_admin_should_return_failure()
{
_userManager.FindByIdAsync(_user.Id.ToString()).Returns(_user);
_userManager.GetRolesAsync(_user).Returns(new List<string> { "Admin" });
_repository.CountAdminUsersAsync(Arg.Any<CancellationToken>()).Returns(1);
var result = await _handler.Handle(new DeleteUserCommand(_user.Id, _currentUserId), CancellationToken.None);
result.IsSuccess.ShouldBeFalse();
result.StatusCode.ShouldBe(400);
}
[Fact]
public async Task Delete_user_when_identity_fails_should_return_failure()
{
_userManager.FindByIdAsync(_user.Id.ToString()).Returns(_user);
_userManager.GetRolesAsync(_user).Returns(new List<string> { "Viewer" });
_userManager.DeleteAsync(_user).Returns(IdentityResult.Failed(new IdentityError { Description = "Delete failed" }));
var result = await _handler.Handle(new DeleteUserCommand(_user.Id, _currentUserId), CancellationToken.None);
result.IsSuccess.ShouldBeFalse();
}
}
@@ -0,0 +1,42 @@
using Heimdall.Application.Common;
using Heimdall.Application.Common.Persistence;
using Heimdall.Application.DTOs;
using Heimdall.Application.Users.Queries.GetMe;
using NSubstitute;
namespace Heimdall.Application.Tests.Handlers.Users;
public class GetMeHandlerTests
{
[Fact]
public async Task Get_me_should_return_user()
{
var userId = Guid.NewGuid();
var userResponse = new UserResponse(userId, "test@test.com", "Test User", "Auto", "fr",
new List<string> { "Admin" }, new List<Guid>(), false, false, null, 0, false, DateTime.UtcNow);
var repository = Substitute.For<IUserRepository>();
repository.GetByIdAsync(userId, Arg.Any<CancellationToken>()).Returns(userResponse);
var handler = new GetMeHandler(repository);
var result = await handler.Handle(new GetMeQuery(userId), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
result.Data.Email.ShouldBe("test@test.com");
result.Data.DisplayName.ShouldBe("Test User");
}
[Fact]
public async Task Get_me_nonexistent_should_return_not_found()
{
var userId = Guid.NewGuid();
var repository = Substitute.For<IUserRepository>();
repository.GetByIdAsync(userId, Arg.Any<CancellationToken>()).Returns((UserResponse?)null);
var handler = new GetMeHandler(repository);
var result = await handler.Handle(new GetMeQuery(userId), CancellationToken.None);
result.IsSuccess.ShouldBeFalse();
result.StatusCode.ShouldBe(404);
}
}
@@ -0,0 +1,40 @@
using Heimdall.Application.Common;
using Heimdall.Application.Common.Persistence;
using Heimdall.Application.DTOs;
using Heimdall.Application.Users.Queries.GetUser;
using NSubstitute;
namespace Heimdall.Application.Tests.Handlers.Users;
public class GetUserHandlerTests
{
[Fact]
public async Task Get_user_should_return_user()
{
var userId = Guid.NewGuid();
var userResponse = new UserResponse(userId, "test@test.com", "Test User", "Auto", "fr",
new List<string>(), new List<Guid>(), false, false, null, 0, false, DateTime.UtcNow);
var repository = Substitute.For<IUserRepository>();
repository.GetByIdAsync(userId, Arg.Any<CancellationToken>()).Returns(userResponse);
var handler = new GetUserHandler(repository);
var result = await handler.Handle(new GetUserQuery(userId), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
result.Data.Id.ShouldBe(userId);
}
[Fact]
public async Task Get_nonexistent_user_should_return_not_found()
{
var repository = Substitute.For<IUserRepository>();
repository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns((UserResponse?)null);
var handler = new GetUserHandler(repository);
var result = await handler.Handle(new GetUserQuery(Guid.NewGuid()), CancellationToken.None);
result.IsSuccess.ShouldBeFalse();
result.StatusCode.ShouldBe(404);
}
}
@@ -0,0 +1,61 @@
using Heimdall.Application.Common;
using Heimdall.Application.Common.Persistence;
using Heimdall.Application.DTOs;
using Heimdall.Application.Users.Queries.GetUsers;
using NSubstitute;
namespace Heimdall.Application.Tests.Handlers.Users;
public class GetUsersHandlerTests
{
[Fact]
public async Task Get_users_should_return_paged_results()
{
var users = new List<UserResponse>
{
new(Guid.NewGuid(), "a@test.com", "Alpha", null, "fr", new List<string>(), new List<Guid>(), false, false, null, 0, false, DateTime.UtcNow),
new(Guid.NewGuid(), "b@test.com", "Beta", null, "en", new List<string>(), new List<Guid>(), false, false, null, 0, false, DateTime.UtcNow),
};
var paged = new PagedResult<UserResponse>(users, 2, 1, 10);
var repository = Substitute.For<IUserRepository>();
repository.GetPagedAsync(1, 10, Arg.Any<CancellationToken>()).Returns(paged);
var handler = new GetUsersHandler(repository);
var result = await handler.Handle(new GetUsersQuery(1, 10), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
result.Data.Items.Count.ShouldBe(2);
result.Data.TotalCount.ShouldBe(2);
}
[Fact]
public async Task Get_users_empty_result_should_return_empty_list()
{
var empty = new PagedResult<UserResponse>(new List<UserResponse>(), 0, 1, 10);
var repository = Substitute.For<IUserRepository>();
repository.GetPagedAsync(1, 10, Arg.Any<CancellationToken>()).Returns(empty);
var handler = new GetUsersHandler(repository);
var result = await handler.Handle(new GetUsersQuery(1, 10), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data!.Items.ShouldBeEmpty();
result.Data.TotalCount.ShouldBe(0);
}
[Fact]
public async Task Get_users_should_respect_pagination()
{
var paged = new PagedResult<UserResponse>(new List<UserResponse>(), 0, 2, 5);
var repository = Substitute.For<IUserRepository>();
repository.GetPagedAsync(2, 5, Arg.Any<CancellationToken>()).Returns(paged);
var handler = new GetUsersHandler(repository);
var result = await handler.Handle(new GetUsersQuery(2, 5), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data!.Page.ShouldBe(2);
result.Data.PageSize.ShouldBe(5);
}
}
@@ -0,0 +1,75 @@
using Heimdall.Application.Common;
using Heimdall.Application.Common.Persistence;
using Heimdall.Application.Users.Commands.UnlockUser;
using Heimdall.Domain.Entities;
using Microsoft.AspNetCore.Identity;
using NSubstitute;
namespace Heimdall.Application.Tests.Handlers.Users;
public class UnlockUserHandlerTests
{
private readonly AppUser _user = new()
{
Id = Guid.NewGuid(),
UserName = "locked@test.com",
Email = "locked@test.com",
LockoutEnd = DateTimeOffset.UtcNow.AddHours(1)
};
private readonly UserManager<AppUser> _userManager;
private readonly IUserRepository _repository;
private readonly UnlockUserHandler _handler;
public UnlockUserHandlerTests()
{
var store = Substitute.For<IUserStore<AppUser>>();
_userManager = Substitute.For<UserManager<AppUser>>(store, null!, null!, null!, null!, null!, null!, null!, null!);
_repository = Substitute.For<IUserRepository>();
_handler = new UnlockUserHandler(_userManager, _repository);
}
[Fact]
public async Task Unlock_user_should_return_success()
{
_userManager.FindByIdAsync(_user.Id.ToString()).Returns(_user);
_userManager.SetLockoutEndDateAsync(_user, null).Returns(IdentityResult.Success);
_userManager.ResetAccessFailedCountAsync(_user).Returns(IdentityResult.Success);
var result = await _handler.Handle(new UnlockUserCommand(_user.Id), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
await _repository.Received(1).AddAuditLogAsync(null, "UserUnlocked", "User",
_user.Id.ToString(), null, null, Arg.Any<CancellationToken>());
}
[Fact]
public async Task Unlock_nonexistent_user_should_return_not_found()
{
_userManager.FindByIdAsync(Arg.Any<string>()).Returns((AppUser?)null);
var result = await _handler.Handle(new UnlockUserCommand(Guid.NewGuid()), CancellationToken.None);
result.IsSuccess.ShouldBeFalse();
result.StatusCode.ShouldBe(404);
}
[Fact]
public async Task Unlock_already_unlocked_user_should_return_success()
{
var unlockedUser = new AppUser
{
Id = Guid.NewGuid(),
UserName = "unlocked@test.com",
Email = "unlocked@test.com",
LockoutEnd = null
};
_userManager.FindByIdAsync(unlockedUser.Id.ToString()).Returns(unlockedUser);
_userManager.SetLockoutEndDateAsync(unlockedUser, null).Returns(IdentityResult.Success);
_userManager.ResetAccessFailedCountAsync(unlockedUser).Returns(IdentityResult.Success);
var result = await _handler.Handle(new UnlockUserCommand(unlockedUser.Id), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
}
}
@@ -0,0 +1,90 @@
using Heimdall.Application.Common;
using Heimdall.Application.Common.Persistence;
using Heimdall.Application.DTOs;
using Heimdall.Application.Users.Commands.UpdateUser;
using Heimdall.Domain.Entities;
using Microsoft.AspNetCore.Identity;
using NSubstitute;
namespace Heimdall.Application.Tests.Handlers.Users;
public class UpdateUserHandlerTests
{
private readonly AppUser _user = new()
{
Id = Guid.NewGuid(),
UserName = "test@test.com",
Email = "test@test.com",
DisplayName = "Old Name",
Theme = "Dark",
Language = "fr"
};
private readonly UserManager<AppUser> _userManager;
private readonly IUserRepository _repository;
private readonly UpdateUserHandler _handler;
public UpdateUserHandlerTests()
{
var store = Substitute.For<IUserStore<AppUser>>();
_userManager = Substitute.For<UserManager<AppUser>>(store, null!, null!, null!, null!, null!, null!, null!, null!);
_repository = Substitute.For<IUserRepository>();
_handler = new UpdateUserHandler(_userManager, _repository);
}
[Fact]
public async Task Update_user_should_return_success()
{
_userManager.FindByIdAsync(_user.Id.ToString()).Returns(_user);
_userManager.UpdateAsync(_user).Returns(IdentityResult.Success);
_repository.GetByIdAsync(_user.Id, Arg.Any<CancellationToken>())
.Returns(new UserResponse(_user.Id, _user.Email!, "New Name", "Light", "en",
new List<string>(), new List<Guid>(), false, false, null, 0, false, DateTime.UtcNow));
var result = await _handler.Handle(
new UpdateUserCommand(_user.Id, "New Name", "Light", "en"), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
result.Data.DisplayName.ShouldBe("New Name");
}
[Fact]
public async Task Update_user_nonexistent_should_return_not_found()
{
_userManager.FindByIdAsync(Arg.Any<string>()).Returns((AppUser?)null);
var result = await _handler.Handle(
new UpdateUserCommand(Guid.NewGuid(), "Name", null, null), CancellationToken.None);
result.IsSuccess.ShouldBeFalse();
result.StatusCode.ShouldBe(404);
}
[Fact]
public async Task Update_user_partial_should_keep_unchanged_values()
{
_userManager.FindByIdAsync(_user.Id.ToString()).Returns(_user);
_userManager.UpdateAsync(_user).Returns(IdentityResult.Success);
_repository.GetByIdAsync(_user.Id, Arg.Any<CancellationToken>())
.Returns(new UserResponse(_user.Id, _user.Email!, "Old Name", "Dark", "fr",
new List<string>(), new List<Guid>(), false, false, null, 0, false, DateTime.UtcNow));
var result = await _handler.Handle(
new UpdateUserCommand(_user.Id, null, "Light", null), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
}
[Fact]
public async Task Update_user_when_identity_fails_should_return_failure()
{
_userManager.FindByIdAsync(_user.Id.ToString()).Returns(_user);
_userManager.UpdateAsync(_user).Returns(IdentityResult.Failed(new IdentityError { Description = "Update failed" }));
var result = await _handler.Handle(
new UpdateUserCommand(_user.Id, "New Name", null, null), CancellationToken.None);
result.IsSuccess.ShouldBeFalse();
}
}
@@ -0,0 +1,108 @@
using Heimdall.TestCommon;
using Microsoft.Playwright;
using Shouldly;
namespace Heimdall.E2E.Tests.Pages;
public class PageRenderTests : E2ETestBase
{
public PageRenderTests(PostgreSqlContainerFixture postgres) : base(postgres) { }
[Fact]
public async Task Sites_page_renders()
{
try
{
await Page.GotoAsync($"{BaseUrl}/sites", new PageGotoOptions { WaitUntil = WaitUntilState.DOMContentLoaded, Timeout = 15000 });
}
catch { /* Protected page may redirect on auth failure */ }
await Task.Delay(3000);
var body = Page.Locator("body");
var text = await body.TextContentAsync();
text.ShouldNotBeNull();
}
[Fact]
public async Task Events_page_renders()
{
try
{
await Page.GotoAsync($"{BaseUrl}/events", new PageGotoOptions { WaitUntil = WaitUntilState.DOMContentLoaded, Timeout = 15000 });
}
catch { }
await Task.Delay(3000);
var body = Page.Locator("body");
var text = await body.TextContentAsync();
text.ShouldNotBeNull();
}
[Fact]
public async Task Profile_page_renders()
{
try
{
await Page.GotoAsync($"{BaseUrl}/profile", new PageGotoOptions { WaitUntil = WaitUntilState.DOMContentLoaded, Timeout = 15000 });
}
catch { }
await Task.Delay(3000);
var body = Page.Locator("body");
var text = await body.TextContentAsync();
text.ShouldNotBeNull();
}
[Fact]
public async Task Settings_page_renders()
{
try
{
await Page.GotoAsync($"{BaseUrl}/settings", new PageGotoOptions { WaitUntil = WaitUntilState.DOMContentLoaded, Timeout = 15000 });
}
catch { }
await Task.Delay(3000);
var body = Page.Locator("body");
var text = await body.TextContentAsync();
text.ShouldNotBeNull();
}
[Fact]
public async Task Admin_groups_page_renders()
{
try
{
await Page.GotoAsync($"{BaseUrl}/admin/groups", new PageGotoOptions { WaitUntil = WaitUntilState.DOMContentLoaded, Timeout = 15000 });
}
catch { }
await Task.Delay(3000);
var body = Page.Locator("body");
var text = await body.TextContentAsync();
text.ShouldNotBeNull();
}
[Fact]
public async Task Cameras_page_renders()
{
try
{
await Page.GotoAsync($"{BaseUrl}/sites/{Guid.NewGuid()}/cameras", new PageGotoOptions { WaitUntil = WaitUntilState.DOMContentLoaded, Timeout = 15000 });
}
catch { }
await Task.Delay(3000);
var body = Page.Locator("body");
var text = await body.TextContentAsync();
text.ShouldNotBeNull();
}
[Fact]
public async Task Agents_page_renders()
{
try
{
await Page.GotoAsync($"{BaseUrl}/sites/{Guid.NewGuid()}/agents", new PageGotoOptions { WaitUntil = WaitUntilState.DOMContentLoaded, Timeout = 15000 });
}
catch { }
await Task.Delay(3000);
var body = Page.Locator("body");
var text = await body.TextContentAsync();
text.ShouldNotBeNull();
}
}