From fed55bb1ab1f334bedc4b919134f2fb830134573 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Thu, 23 Jul 2026 14:32:33 +0000 Subject: [PATCH] test(application): add CQRS handler tests for Sites, Cameras, Agents, Auth, Events, Settings, Groups, Users, Assignments, Discovery, Persons, Stats, Audit --- .../Common/CameraEventHelper.cs | 42 +++++++ .../Common/MockDbSetHelper.cs | 62 +++++++++- .../Handlers/Agents/GetAgentHandlerTests.cs | 42 +++++++ .../Agents/GetAgentsBySiteHandlerTests.cs | 69 +++++++++++ .../Agents/GetAllAgentsHandlerTests.cs | 81 ++++++++++++ .../Handlers/Agents/HeartbeatHandlerTests.cs | 86 +++++++++++++ .../Agents/RegisterAgentHandlerTests.cs | 116 ++++++++++++++++++ .../Auth/ChangePasswordHandlerTests.cs | 65 ++++++++++ .../Handlers/Auth/LoginHandlerTests.cs | 110 +++++++++++++++++ .../Handlers/Auth/RefreshTokenHandlerTests.cs | 92 ++++++++++++++ .../Auth/RegisterAdminHandlerTests.cs | 74 +++++++++++ .../Handlers/Auth/RegisterHandlerTests.cs | 100 +++++++++++++++ .../Cameras/CreateCameraHandlerTests.cs | 57 +++++++++ .../Cameras/DeleteCameraHandlerTests.cs | 54 ++++++++ .../Handlers/Cameras/GetCameraHandlerTests.cs | 42 +++++++ .../Cameras/GetCamerasBySiteHandlerTests.cs | 83 +++++++++++++ .../SetCameraCredentialsHandlerTests.cs | 77 ++++++++++++ .../Cameras/UpdateCameraHandlerTests.cs | 70 +++++++++++ .../Events/AttachSnapshotHandlerTests.cs | 41 +++++++ .../Events/CreateEventHandlerTests.cs | 67 ++++++++++ .../Events/DeleteEventHandlerTests.cs | 38 ++++++ .../Handlers/Events/GetEventHandlerTests.cs | 44 +++++++ .../Handlers/Events/GetEventsHandlerTests.cs | 60 +++++++++ .../Events/GetRecentByCameraHandlerTests.cs | 51 ++++++++ .../Settings/CreateAppSettingHandlerTests.cs | 43 +++++++ .../Settings/DeleteAppSettingHandlerTests.cs | 37 ++++++ .../Settings/GetAgentSettingsHandlerTests.cs | 46 +++++++ .../GetEffectiveAgentConfigHandlerTests.cs | 38 ++++++ .../Settings/GetSettingByKeyHandlerTests.cs | 38 ++++++ .../Settings/GetSettingsHandlerTests.cs | 30 +++++ .../RemoveAgentSettingHandlerTests.cs | 40 ++++++ .../Settings/SetAgentSettingHandlerTests.cs | 45 +++++++ .../Settings/UpdateAppSettingHandlerTests.cs | 41 +++++++ .../Handlers/Sites/DeleteSiteHandlerTests.cs | 54 ++++++++ .../Handlers/Sites/GetSiteHandlerTests.cs | 43 +++++++ .../Handlers/Sites/GetSitesHandlerTests.cs | 79 ++++++++++++ .../Handlers/Sites/UpdateSiteHandlerTests.cs | 57 +++++++++ 37 files changed, 2209 insertions(+), 5 deletions(-) create mode 100644 tests/Heimdall.Application.Tests/Common/CameraEventHelper.cs create mode 100644 tests/Heimdall.Application.Tests/Handlers/Agents/GetAgentHandlerTests.cs create mode 100644 tests/Heimdall.Application.Tests/Handlers/Agents/GetAgentsBySiteHandlerTests.cs create mode 100644 tests/Heimdall.Application.Tests/Handlers/Agents/GetAllAgentsHandlerTests.cs create mode 100644 tests/Heimdall.Application.Tests/Handlers/Agents/HeartbeatHandlerTests.cs create mode 100644 tests/Heimdall.Application.Tests/Handlers/Agents/RegisterAgentHandlerTests.cs create mode 100644 tests/Heimdall.Application.Tests/Handlers/Auth/ChangePasswordHandlerTests.cs create mode 100644 tests/Heimdall.Application.Tests/Handlers/Auth/LoginHandlerTests.cs create mode 100644 tests/Heimdall.Application.Tests/Handlers/Auth/RefreshTokenHandlerTests.cs create mode 100644 tests/Heimdall.Application.Tests/Handlers/Auth/RegisterAdminHandlerTests.cs create mode 100644 tests/Heimdall.Application.Tests/Handlers/Auth/RegisterHandlerTests.cs create mode 100644 tests/Heimdall.Application.Tests/Handlers/Cameras/CreateCameraHandlerTests.cs create mode 100644 tests/Heimdall.Application.Tests/Handlers/Cameras/DeleteCameraHandlerTests.cs create mode 100644 tests/Heimdall.Application.Tests/Handlers/Cameras/GetCameraHandlerTests.cs create mode 100644 tests/Heimdall.Application.Tests/Handlers/Cameras/GetCamerasBySiteHandlerTests.cs create mode 100644 tests/Heimdall.Application.Tests/Handlers/Cameras/SetCameraCredentialsHandlerTests.cs create mode 100644 tests/Heimdall.Application.Tests/Handlers/Cameras/UpdateCameraHandlerTests.cs create mode 100644 tests/Heimdall.Application.Tests/Handlers/Events/AttachSnapshotHandlerTests.cs create mode 100644 tests/Heimdall.Application.Tests/Handlers/Events/CreateEventHandlerTests.cs create mode 100644 tests/Heimdall.Application.Tests/Handlers/Events/DeleteEventHandlerTests.cs create mode 100644 tests/Heimdall.Application.Tests/Handlers/Events/GetEventHandlerTests.cs create mode 100644 tests/Heimdall.Application.Tests/Handlers/Events/GetEventsHandlerTests.cs create mode 100644 tests/Heimdall.Application.Tests/Handlers/Events/GetRecentByCameraHandlerTests.cs create mode 100644 tests/Heimdall.Application.Tests/Handlers/Settings/CreateAppSettingHandlerTests.cs create mode 100644 tests/Heimdall.Application.Tests/Handlers/Settings/DeleteAppSettingHandlerTests.cs create mode 100644 tests/Heimdall.Application.Tests/Handlers/Settings/GetAgentSettingsHandlerTests.cs create mode 100644 tests/Heimdall.Application.Tests/Handlers/Settings/GetEffectiveAgentConfigHandlerTests.cs create mode 100644 tests/Heimdall.Application.Tests/Handlers/Settings/GetSettingByKeyHandlerTests.cs create mode 100644 tests/Heimdall.Application.Tests/Handlers/Settings/GetSettingsHandlerTests.cs create mode 100644 tests/Heimdall.Application.Tests/Handlers/Settings/RemoveAgentSettingHandlerTests.cs create mode 100644 tests/Heimdall.Application.Tests/Handlers/Settings/SetAgentSettingHandlerTests.cs create mode 100644 tests/Heimdall.Application.Tests/Handlers/Settings/UpdateAppSettingHandlerTests.cs create mode 100644 tests/Heimdall.Application.Tests/Handlers/Sites/DeleteSiteHandlerTests.cs create mode 100644 tests/Heimdall.Application.Tests/Handlers/Sites/GetSiteHandlerTests.cs create mode 100644 tests/Heimdall.Application.Tests/Handlers/Sites/GetSitesHandlerTests.cs create mode 100644 tests/Heimdall.Application.Tests/Handlers/Sites/UpdateSiteHandlerTests.cs diff --git a/tests/Heimdall.Application.Tests/Common/CameraEventHelper.cs b/tests/Heimdall.Application.Tests/Common/CameraEventHelper.cs new file mode 100644 index 0000000..0b88187 --- /dev/null +++ b/tests/Heimdall.Application.Tests/Common/CameraEventHelper.cs @@ -0,0 +1,42 @@ +using System.Reflection; +using Heimdall.Domain.Entities; +using Microsoft.EntityFrameworkCore; + +namespace Heimdall.Application.Tests.Common; + +public static class CameraEventHelper +{ + public static void SetCamera(this CameraEvent ev, Camera camera) + { + var field = typeof(CameraEvent).GetField("k__BackingField", + BindingFlags.Instance | BindingFlags.NonPublic); + if (field is not null) + { + field.SetValue(ev, camera); + } + else + { + var prop = typeof(CameraEvent).GetProperty("Camera", + BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); + prop?.SetValue(ev, camera); + } + } +} + +public class CameraAwareDbSet : InMemoryDbSet +{ + private readonly Func _cameraLookup; + + public CameraAwareDbSet(IEnumerable data, Func cameraLookup) + : base(data) + { + _cameraLookup = cameraLookup; + } + + protected override void OnBeforeAdd(CameraEvent entity) + { + var camera = _cameraLookup(entity.CameraId); + if (camera is not null) + entity.SetCamera(camera); + } +} diff --git a/tests/Heimdall.Application.Tests/Common/MockDbSetHelper.cs b/tests/Heimdall.Application.Tests/Common/MockDbSetHelper.cs index f1909f7..d9ca7d4 100644 --- a/tests/Heimdall.Application.Tests/Common/MockDbSetHelper.cs +++ b/tests/Heimdall.Application.Tests/Common/MockDbSetHelper.cs @@ -8,6 +8,8 @@ using Microsoft.EntityFrameworkCore.Query; using NSubstitute; using NSubstitute.Core; +#pragma warning disable CA1051 // Visible instance fields needed for subclass access + namespace Heimdall.Application.Tests.Common; /// @@ -26,14 +28,16 @@ public static class MockDbSetHelper /// In-memory DbSet implementation that properly handles explicit IQueryable interface. /// Uses NSubstitute to wrap a real queryable, ensuring EF Core async operations work. /// -internal sealed class InMemoryDbSet : DbSet, IQueryable, IAsyncEnumerable +public class InMemoryDbSet : DbSet, IQueryable, IAsyncEnumerable where T : class { - private readonly List _data; + protected readonly List _data; public InMemoryDbSet() : this([]) { } public InMemoryDbSet(IEnumerable data) { _data = data.ToList(); } + protected virtual void OnBeforeAdd(T entity) { } + // IQueryable — explicit implementation via NSubstitute wrapper Type IQueryable.ElementType => typeof(T); Expression IQueryable.Expression => _data.AsQueryable().Expression; @@ -49,7 +53,7 @@ internal sealed class InMemoryDbSet : DbSet, IQueryable, IAsyncEnumerab // DbSet abstract members public override IEntityType EntityType => null!; - public override EntityEntry Add(T entity) { _data.Add(entity); return null!; } + public override EntityEntry Add(T entity) { OnBeforeAdd(entity); _data.Add(entity); return null!; } public override EntityEntry Remove(T entity) { _data.Remove(entity); return null!; } public override ValueTask FindAsync(object?[]? keyValues, CancellationToken ct = default) { @@ -68,8 +72,10 @@ internal sealed class InMemoryAsyncQueryProvider : IAsyncQueryProvider private readonly IQueryProvider _inner; public InMemoryAsyncQueryProvider(IQueryProvider inner) => _inner = inner; - public IQueryable CreateQuery(Expression expression) => _inner.CreateQuery(expression); - public IQueryable CreateQuery(Expression expression) => _inner.CreateQuery(expression); + public IQueryable CreateQuery(Expression expression) => + new InMemoryAsyncQueryable(expression, this); + public IQueryable CreateQuery(Expression expression) => + new InMemoryAsyncQueryable(expression, new InMemoryAsyncQueryProvider(_inner)); public object? Execute(Expression expression) => _inner.Execute(expression); public TResult Execute(Expression expression) => _inner.Execute(expression); @@ -85,6 +91,52 @@ internal sealed class InMemoryAsyncQueryProvider : IAsyncQueryProvider } } +internal sealed class InMemoryAsyncQueryable : IOrderedQueryable, IAsyncEnumerable +{ + private readonly Expression _expression; + private readonly IAsyncQueryProvider _provider; + + public InMemoryAsyncQueryable(Expression expression, IAsyncQueryProvider provider) + { + _expression = expression; + _provider = provider; + } + + public Type ElementType => typeof(object); + public Expression Expression => _expression; + public IQueryProvider Provider => _provider; + + public IEnumerator GetEnumerator() => + ((IEnumerable)_provider.Execute(_expression)!).GetEnumerator(); + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + + public IAsyncEnumerator GetAsyncEnumerator(CancellationToken ct = default) => + new InMemoryAsyncEnumerator(GetEnumerator()); +} + +internal sealed class InMemoryAsyncQueryable : IOrderedQueryable, IAsyncEnumerable +{ + private readonly Expression _expression; + private readonly InMemoryAsyncQueryProvider _provider; + + public InMemoryAsyncQueryable(Expression expression, InMemoryAsyncQueryProvider provider) + { + _expression = expression; + _provider = provider; + } + + public Type ElementType => typeof(TElement); + public Expression Expression => _expression; + public IQueryProvider Provider => _provider; + + public IEnumerator GetEnumerator() => + _provider.Execute>(_expression)!.GetEnumerator(); + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + + public IAsyncEnumerator GetAsyncEnumerator(CancellationToken ct = default) => + new InMemoryAsyncEnumerator(GetEnumerator()); +} + internal sealed class InMemoryAsyncEnumerator : IAsyncEnumerator { private readonly IEnumerator _inner; diff --git a/tests/Heimdall.Application.Tests/Handlers/Agents/GetAgentHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Agents/GetAgentHandlerTests.cs new file mode 100644 index 0000000..d1cb1d2 --- /dev/null +++ b/tests/Heimdall.Application.Tests/Handlers/Agents/GetAgentHandlerTests.cs @@ -0,0 +1,42 @@ +using Heimdall.Application.Agents.Queries.GetAgent; +using Heimdall.Application.Common; +using Heimdall.Application.Tests.Common; +using Heimdall.Domain.Entities; +using NSubstitute; + +namespace Heimdall.Application.Tests.Handlers.Agents; + +public class GetAgentHandlerTests +{ + private readonly Agent _existingAgent = new(Guid.NewGuid(), "agent-1", "agent-host-1", "2.0.0"); + + [Fact] + public async Task Get_agent_should_return_agent() + { + var context = Substitute.For(); + context.Agents.Returns(MockDbSetHelper.CreateFor([_existingAgent])); + var handler = new GetAgentHandler(context); + var query = new GetAgentQuery(_existingAgent.Id); + + var result = await handler.Handle(query, CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + result.Data.ShouldNotBeNull(); + result.Data.Name.ShouldBe("agent-1"); + result.Data.Hostname.ShouldBe("agent-host-1"); + } + + [Fact] + public async Task Get_nonexistent_agent_should_return_not_found() + { + var context = Substitute.For(); + context.Agents.Returns(MockDbSetHelper.CreateFor([_existingAgent])); + var handler = new GetAgentHandler(context); + var query = new GetAgentQuery(Guid.NewGuid()); + + var result = await handler.Handle(query, CancellationToken.None); + + result.IsSuccess.ShouldBeFalse(); + result.StatusCode.ShouldBe(404); + } +} diff --git a/tests/Heimdall.Application.Tests/Handlers/Agents/GetAgentsBySiteHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Agents/GetAgentsBySiteHandlerTests.cs new file mode 100644 index 0000000..eddb513 --- /dev/null +++ b/tests/Heimdall.Application.Tests/Handlers/Agents/GetAgentsBySiteHandlerTests.cs @@ -0,0 +1,69 @@ +using Heimdall.Application.Agents.Queries.GetAgentsBySite; +using Heimdall.Application.Common; +using Heimdall.Application.Tests.Common; +using Heimdall.Domain.Entities; +using NSubstitute; + +namespace Heimdall.Application.Tests.Handlers.Agents; + +public class GetAgentsBySiteHandlerTests +{ + private readonly Guid _siteId = Guid.NewGuid(); + private readonly Guid _otherSiteId = Guid.NewGuid(); + private readonly List _agents; + + public GetAgentsBySiteHandlerTests() + { + _agents = + [ + new Agent(_siteId, "Beta Agent", "beta-host", "1.0.0"), + new Agent(_siteId, "Alpha Agent", "alpha-host", "2.0.0"), + new Agent(_otherSiteId, "Other Agent", "other-host", "1.5.0"), + ]; + } + + [Fact] + public async Task Get_agents_by_site_should_return_site_agents() + { + var context = Substitute.For(); + context.Agents.Returns(MockDbSetHelper.CreateFor(_agents)); + var handler = new GetAgentsBySiteHandler(context); + var query = new GetAgentsBySiteQuery(_siteId, Page: 1, PageSize: 20); + + var result = await handler.Handle(query, CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + result.Data.ShouldNotBeNull(); + result.Data.Items.Count.ShouldBe(2); + result.Data.TotalCount.ShouldBe(2); + } + + [Fact] + public async Task Get_agents_by_site_should_order_by_name() + { + var context = Substitute.For(); + context.Agents.Returns(MockDbSetHelper.CreateFor(_agents)); + var handler = new GetAgentsBySiteHandler(context); + var query = new GetAgentsBySiteQuery(_siteId, Page: 1, PageSize: 20); + + var result = await handler.Handle(query, CancellationToken.None); + + result.Data!.Items[0].Name.ShouldBe("Alpha Agent"); + result.Data.Items[1].Name.ShouldBe("Beta Agent"); + } + + [Fact] + public async Task Get_agents_by_site_should_return_empty_for_site_with_no_agents() + { + var context = Substitute.For(); + context.Agents.Returns(MockDbSetHelper.CreateFor(_agents)); + var handler = new GetAgentsBySiteHandler(context); + var query = new GetAgentsBySiteQuery(Guid.NewGuid(), Page: 1, PageSize: 20); + + var result = await handler.Handle(query, CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + result.Data!.Items.ShouldBeEmpty(); + result.Data.TotalCount.ShouldBe(0); + } +} diff --git a/tests/Heimdall.Application.Tests/Handlers/Agents/GetAllAgentsHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Agents/GetAllAgentsHandlerTests.cs new file mode 100644 index 0000000..e1b0e87 --- /dev/null +++ b/tests/Heimdall.Application.Tests/Handlers/Agents/GetAllAgentsHandlerTests.cs @@ -0,0 +1,81 @@ +using Heimdall.Application.Agents.Queries.GetAllAgents; +using Heimdall.Application.Common; +using Heimdall.Application.Tests.Common; +using Heimdall.Domain.Entities; +using NSubstitute; + +namespace Heimdall.Application.Tests.Handlers.Agents; + +public class GetAllAgentsHandlerTests +{ + private readonly List _agents; + + public GetAllAgentsHandlerTests() + { + _agents = + [ + new Agent(Guid.NewGuid(), "Charlie", "charlie-host", "1.0.0"), + new Agent(Guid.NewGuid(), "Alpha", "alpha-host", "2.0.0"), + new Agent(Guid.NewGuid(), "Bravo", "bravo-host", "1.5.0"), + ]; + } + + [Fact] + public async Task Get_all_agents_should_return_all_agents() + { + var context = Substitute.For(); + context.Agents.Returns(MockDbSetHelper.CreateFor(_agents)); + var handler = new GetAllAgentsHandler(context); + var query = new GetAllAgentsQuery(Page: 1, PageSize: 20); + + var result = await handler.Handle(query, CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + result.Data.ShouldNotBeNull(); + result.Data.TotalCount.ShouldBe(3); + } + + [Fact] + public async Task Get_all_agents_should_order_by_name() + { + var context = Substitute.For(); + context.Agents.Returns(MockDbSetHelper.CreateFor(_agents)); + var handler = new GetAllAgentsHandler(context); + var query = new GetAllAgentsQuery(Page: 1, PageSize: 20); + + var result = await handler.Handle(query, CancellationToken.None); + + result.Data!.Items[0].Name.ShouldBe("Alpha"); + result.Data.Items[1].Name.ShouldBe("Bravo"); + result.Data.Items[2].Name.ShouldBe("Charlie"); + } + + [Fact] + public async Task Get_all_agents_should_respect_pagination() + { + var context = Substitute.For(); + context.Agents.Returns(MockDbSetHelper.CreateFor(_agents)); + var handler = new GetAllAgentsHandler(context); + var query = new GetAllAgentsQuery(Page: 1, PageSize: 2); + + var result = await handler.Handle(query, CancellationToken.None); + + result.Data!.Items.Count.ShouldBe(2); + result.Data.TotalCount.ShouldBe(3); + } + + [Fact] + public async Task Get_all_agents_empty_result_should_return_empty_list() + { + var context = Substitute.For(); + context.Agents.Returns(MockDbSetHelper.CreateFor()); + var handler = new GetAllAgentsHandler(context); + var query = new GetAllAgentsQuery(Page: 1, PageSize: 20); + + var result = await handler.Handle(query, CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + result.Data!.Items.ShouldBeEmpty(); + result.Data.TotalCount.ShouldBe(0); + } +} diff --git a/tests/Heimdall.Application.Tests/Handlers/Agents/HeartbeatHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Agents/HeartbeatHandlerTests.cs new file mode 100644 index 0000000..ea14a45 --- /dev/null +++ b/tests/Heimdall.Application.Tests/Handlers/Agents/HeartbeatHandlerTests.cs @@ -0,0 +1,86 @@ +using Heimdall.Application.Agents.Commands.Heartbeat; +using Heimdall.Application.Common; +using Heimdall.Application.Tests.Common; +using Heimdall.Domain.Entities; +using Heimdall.Domain.Enums; +using NSubstitute; +using Microsoft.EntityFrameworkCore; + +namespace Heimdall.Application.Tests.Handlers.Agents; + +public class HeartbeatHandlerTests +{ + private readonly Agent _existingAgent = new(Guid.NewGuid(), "agent-1", "agent-1", "1.0.0"); + + [Fact] + public async Task Heartbeat_should_return_success() + { + var context = Substitute.For(); + context.Agents.Returns(MockDbSetHelper.CreateFor([_existingAgent])); + var handler = new HeartbeatHandler(context); + var command = new HeartbeatCommand(_existingAgent.Id, "203.0.113.1", null, null, null, null); + + var result = await handler.Handle(command, CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + } + + [Fact] + public async Task Heartbeat_nonexistent_agent_should_return_not_found() + { + var context = Substitute.For(); + context.Agents.Returns(MockDbSetHelper.CreateFor([_existingAgent])); + var handler = new HeartbeatHandler(context); + var command = new HeartbeatCommand(Guid.NewGuid(), null, null, null, null, null); + + var result = await handler.Handle(command, CancellationToken.None); + + result.IsSuccess.ShouldBeFalse(); + result.StatusCode.ShouldBe(404); + } + + [Fact] + public async Task Heartbeat_should_update_agent_status() + { + _existingAgent.MarkOffline(); + var context = Substitute.For(); + context.Agents.Returns(MockDbSetHelper.CreateFor([_existingAgent])); + var handler = new HeartbeatHandler(context); + var command = new HeartbeatCommand(_existingAgent.Id, "10.0.0.1", null, null, null, null); + + await handler.Handle(command, CancellationToken.None); + + _existingAgent.Status.ShouldBe(AgentStatus.Online); + _existingAgent.LastHeartbeat.ShouldNotBeNull(); + _existingAgent.PublicIp.ShouldBe("10.0.0.1"); + } + + [Fact] + public async Task Heartbeat_should_update_capabilities_when_provided() + { + var context = Substitute.For(); + context.Agents.Returns(MockDbSetHelper.CreateFor([_existingAgent])); + var handler = new HeartbeatHandler(context); + var command = new HeartbeatCommand(_existingAgent.Id, null, true, 8, 16384, GpuAcceleration.NvidiaCuda); + + await handler.Handle(command, CancellationToken.None); + + _existingAgent.HasGpu.ShouldBeTrue(); + _existingAgent.CpuCores.ShouldBe(8); + _existingAgent.MemoryMb.ShouldBe(16384); + _existingAgent.GpuType.ShouldBe(GpuAcceleration.NvidiaCuda); + } + + [Fact] + public async Task Heartbeat_should_save_changes() + { + var context = Substitute.For(); + context.Agents.Returns(MockDbSetHelper.CreateFor([_existingAgent])); + var handler = new HeartbeatHandler(context); + var command = new HeartbeatCommand(_existingAgent.Id, null, null, null, null, null); + + await handler.Handle(command, CancellationToken.None); + + await context.Received(1).SaveChangesWithRetryAsync(Arg.Any(), Arg.Any()); + } +} diff --git a/tests/Heimdall.Application.Tests/Handlers/Agents/RegisterAgentHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Agents/RegisterAgentHandlerTests.cs new file mode 100644 index 0000000..d2f2a63 --- /dev/null +++ b/tests/Heimdall.Application.Tests/Handlers/Agents/RegisterAgentHandlerTests.cs @@ -0,0 +1,116 @@ +using System.Security.Cryptography; +using System.Text; +using Heimdall.Application.Agents.Commands.RegisterAgent; +using Heimdall.Application.Common; +using Heimdall.Application.Tests.Common; +using Heimdall.Domain.Entities; +using NSubstitute; +using Microsoft.EntityFrameworkCore; + +namespace Heimdall.Application.Tests.Handlers.Agents; + +public class RegisterAgentHandlerTests +{ + private static Site MakeSiteWithToken() + { + var site = new Site("Test Site", "Paris", "Europe/Paris"); + var token = "valid-registration-token"; + var hash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(token))).ToLowerInvariant(); + site.GenerateRegistrationToken(hash, DateTime.UtcNow.AddHours(1)); + return site; + } + + [Fact] + public async Task Register_agent_should_return_success() + { + var site = MakeSiteWithToken(); + var context = Substitute.For(); + context.Sites.Returns(MockDbSetHelper.CreateFor([site])); + context.Agents.Returns(MockDbSetHelper.CreateFor()); + context.ApiKeys.Returns(MockDbSetHelper.CreateFor()); + context.AuditLogs.Returns(MockDbSetHelper.CreateFor()); + + var handler = new RegisterAgentHandler(context); + var command = new RegisterAgentCommand("valid-registration-token", "agent-host-1", "1.0.0", "192.168.1.50"); + + var result = await handler.Handle(command, CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + result.Data.ShouldNotBeNull(); + result.Data.ApiKeyPrefix.Length.ShouldBe(8); + } + + [Fact] + public async Task Register_agent_invalid_token_should_return_unauthorized() + { + var site = MakeSiteWithToken(); + var context = Substitute.For(); + context.Sites.Returns(MockDbSetHelper.CreateFor([site])); + context.Agents.Returns(MockDbSetHelper.CreateFor()); + + var handler = new RegisterAgentHandler(context); + var command = new RegisterAgentCommand("wrong-token", "agent-host-1", "1.0.0", null); + + var result = await handler.Handle(command, CancellationToken.None); + + result.IsSuccess.ShouldBeFalse(); + result.StatusCode.ShouldBe(401); + } + + [Fact] + public async Task Register_agent_duplicate_hostname_should_return_conflict() + { + var site = MakeSiteWithToken(); + var existingAgent = new Agent(site.Id, "agent-host-1", "agent-host-1", "1.0.0"); + var context = Substitute.For(); + context.Sites.Returns(MockDbSetHelper.CreateFor([site])); + context.Agents.Returns(MockDbSetHelper.CreateFor([existingAgent])); + context.ApiKeys.Returns(MockDbSetHelper.CreateFor()); + context.AuditLogs.Returns(MockDbSetHelper.CreateFor()); + + var handler = new RegisterAgentHandler(context); + var command = new RegisterAgentCommand("valid-registration-token", "agent-host-1", "1.0.0", "10.0.0.1"); + + var result = await handler.Handle(command, CancellationToken.None); + + result.IsSuccess.ShouldBeFalse(); + result.StatusCode.ShouldBe(409); + } + + [Fact] + public async Task Register_agent_should_clear_site_token() + { + var site = MakeSiteWithToken(); + var context = Substitute.For(); + context.Sites.Returns(MockDbSetHelper.CreateFor([site])); + context.Agents.Returns(MockDbSetHelper.CreateFor()); + context.ApiKeys.Returns(MockDbSetHelper.CreateFor()); + context.AuditLogs.Returns(MockDbSetHelper.CreateFor()); + + var handler = new RegisterAgentHandler(context); + var command = new RegisterAgentCommand("valid-registration-token", "new-agent", "1.0.0", null); + + await handler.Handle(command, CancellationToken.None); + + site.RegistrationTokenHash.ShouldBeNull(); + site.TokenExpiresAt.ShouldBeNull(); + } + + [Fact] + public async Task Register_agent_should_save_changes() + { + var site = MakeSiteWithToken(); + var context = Substitute.For(); + context.Sites.Returns(MockDbSetHelper.CreateFor([site])); + context.Agents.Returns(MockDbSetHelper.CreateFor()); + context.ApiKeys.Returns(MockDbSetHelper.CreateFor()); + context.AuditLogs.Returns(MockDbSetHelper.CreateFor()); + + var handler = new RegisterAgentHandler(context); + var command = new RegisterAgentCommand("valid-registration-token", "new-agent", "1.0.0", null); + + await handler.Handle(command, CancellationToken.None); + + await context.Received(1).SaveChangesWithRetryAsync(Arg.Any(), Arg.Any()); + } +} diff --git a/tests/Heimdall.Application.Tests/Handlers/Auth/ChangePasswordHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Auth/ChangePasswordHandlerTests.cs new file mode 100644 index 0000000..d431571 --- /dev/null +++ b/tests/Heimdall.Application.Tests/Handlers/Auth/ChangePasswordHandlerTests.cs @@ -0,0 +1,65 @@ +using Heimdall.Application.Auth.Commands.ChangePassword; +using Heimdall.Domain.Entities; +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.Logging; +using NSubstitute; + +namespace Heimdall.Application.Tests.Handlers.Auth; + +public class ChangePasswordHandlerTests +{ + private readonly UserManager _userManager; + private readonly ILogger _logger; + private readonly ChangePasswordHandler _handler; + + public ChangePasswordHandlerTests() + { + var userStore = Substitute.For>(); + var identityOptions = Microsoft.Extensions.Options.Options.Create(new IdentityOptions()); + _userManager = Substitute.For>(userStore, identityOptions, null!, null!, null!, null!, null!, null!, null!); + _logger = Substitute.For>(); + _handler = new ChangePasswordHandler(_userManager, _logger); + } + + [Fact] + public async Task Change_password_with_valid_data_should_return_success() + { + var user = new AppUser { Id = Guid.NewGuid() }; + _userManager.FindByIdAsync(user.Id.ToString()).Returns(user); + _userManager.ChangePasswordAsync(user, "old-password", "new-password") + .Returns(IdentityResult.Success); + + var result = await _handler.Handle( + new ChangePasswordCommand(user.Id, "old-password", "new-password"), CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + } + + [Fact] + public async Task Change_password_for_unknown_user_should_return_not_found() + { + var userId = Guid.NewGuid(); + _userManager.FindByIdAsync(userId.ToString()).Returns((AppUser?)null); + + var result = await _handler.Handle( + new ChangePasswordCommand(userId, "old", "new"), CancellationToken.None); + + result.IsSuccess.ShouldBeFalse(); + result.StatusCode.ShouldBe(404); + } + + [Fact] + public async Task Change_password_when_change_fails_should_return_error() + { + var user = new AppUser { Id = Guid.NewGuid() }; + _userManager.FindByIdAsync(user.Id.ToString()).Returns(user); + _userManager.ChangePasswordAsync(user, "wrong", "new") + .Returns(IdentityResult.Failed(new IdentityError { Description = "Incorrect password" })); + + var result = await _handler.Handle( + new ChangePasswordCommand(user.Id, "wrong", "new"), CancellationToken.None); + + result.IsSuccess.ShouldBeFalse(); + result.Error!.ShouldContain("Incorrect password"); + } +} diff --git a/tests/Heimdall.Application.Tests/Handlers/Auth/LoginHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Auth/LoginHandlerTests.cs new file mode 100644 index 0000000..00aeb47 --- /dev/null +++ b/tests/Heimdall.Application.Tests/Handlers/Auth/LoginHandlerTests.cs @@ -0,0 +1,110 @@ +using System.Security.Claims; +using Heimdall.Application.Auth.Commands.Login; +using Heimdall.Application.DTOs; +using Heimdall.Application.Services; +using Heimdall.Domain.Entities; +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.Logging; +using NSubstitute; + +namespace Heimdall.Application.Tests.Handlers.Auth; + +public class LoginHandlerTests +{ + private readonly UserManager _userManager; + private readonly IAuthSignInService _signInService; + private readonly IJwtService _jwtService; + private readonly IRolePermissionService _rolePermissionService; + private readonly ILogger _logger; + private readonly LoginHandler _handler; + + public LoginHandlerTests() + { + var userStore = Substitute.For>(); + var identityOptions = Microsoft.Extensions.Options.Options.Create(new IdentityOptions()); + _userManager = Substitute.For>(userStore, identityOptions, null!, null!, null!, null!, null!, null!, null!); + _signInService = Substitute.For(); + _jwtService = Substitute.For(); + _rolePermissionService = Substitute.For(); + _logger = Substitute.For>(); + _handler = new LoginHandler(_userManager, _signInService, _jwtService, _rolePermissionService, _logger); + } + + [Fact] + public async Task Login_with_valid_credentials_should_return_success() + { + var user = new AppUser { UserName = "test@test.com", Email = "test@test.com", DisplayName = "Test" }; + _userManager.FindByEmailAsync("test@test.com").Returns(user); + _userManager.IsLockedOutAsync(user).Returns(false); + _userManager.GetTwoFactorEnabledAsync(user).Returns(false); + _userManager.GetRolesAsync(user).Returns(["Viewer"]); + _signInService.PasswordSignInAsync(user, "password", true) + .Returns(new SignInServiceResult(SignInResultType.Success)); + _jwtService.GenerateAccessToken(user, Arg.Any>(), Arg.Any>()) + .Returns(("access-token", DateTime.UtcNow.AddHours(1))); + _jwtService.GenerateRefreshToken(user).Returns(("refresh-token", DateTime.UtcNow.AddDays(7))); + _rolePermissionService.GetPermissionsForRoles(Arg.Any>()).Returns([]); + + var result = await _handler.Handle(new LoginCommand("test@test.com", "password"), CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + result.Data.ShouldNotBeNull(); + result.Data.AccessToken.ShouldBe("access-token"); + } + + [Fact] + public async Task Login_with_unknown_email_should_return_unauthorized() + { + _userManager.FindByEmailAsync("unknown@test.com").Returns((AppUser?)null); + + var result = await _handler.Handle(new LoginCommand("unknown@test.com", "password"), CancellationToken.None); + + result.IsSuccess.ShouldBeFalse(); + result.StatusCode.ShouldBe(401); + } + + [Fact] + public async Task Login_with_locked_account_should_return_429() + { + var user = new AppUser { UserName = "locked@test.com", Email = "locked@test.com" }; + _userManager.FindByEmailAsync("locked@test.com").Returns(user); + _userManager.IsLockedOutAsync(user).Returns(true); + + var result = await _handler.Handle(new LoginCommand("locked@test.com", "password"), CancellationToken.None); + + result.IsSuccess.ShouldBeFalse(); + result.StatusCode.ShouldBe(429); + } + + [Fact] + public async Task Login_with_2fa_enabled_should_require_2fa() + { + var user = new AppUser { UserName = "2fa@test.com", Email = "2fa@test.com" }; + _userManager.FindByEmailAsync("2fa@test.com").Returns(user); + _userManager.IsLockedOutAsync(user).Returns(false); + _userManager.GetTwoFactorEnabledAsync(user).Returns(true); + _signInService.PasswordSignInAsync(user, "password", true) + .Returns(new SignInServiceResult(SignInResultType.Success)); + + var result = await _handler.Handle(new LoginCommand("2fa@test.com", "password"), CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + result.Data!.Requires2fa.ShouldBeTrue(); + } + + [Fact] + public async Task Login_with_wrong_password_should_return_unauthorized() + { + var user = new AppUser { UserName = "test@test.com", Email = "test@test.com" }; + _userManager.FindByEmailAsync("test@test.com").Returns(user); + _userManager.IsLockedOutAsync(user).Returns(false); + _userManager.GetTwoFactorEnabledAsync(user).Returns(false); + _signInService.PasswordSignInAsync(user, "wrong", true) + .Returns(new SignInServiceResult(SignInResultType.Failed)); + + var result = await _handler.Handle(new LoginCommand("test@test.com", "wrong"), CancellationToken.None); + + result.IsSuccess.ShouldBeFalse(); + result.StatusCode.ShouldBe(401); + } +} diff --git a/tests/Heimdall.Application.Tests/Handlers/Auth/RefreshTokenHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Auth/RefreshTokenHandlerTests.cs new file mode 100644 index 0000000..fdce098 --- /dev/null +++ b/tests/Heimdall.Application.Tests/Handlers/Auth/RefreshTokenHandlerTests.cs @@ -0,0 +1,92 @@ +using System.Security.Claims; +using Heimdall.Application.Auth.Commands.RefreshToken; +using Heimdall.Application.DTOs; +using Heimdall.Application.Services; +using Heimdall.Domain.Entities; +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.Logging; +using NSubstitute; + +namespace Heimdall.Application.Tests.Handlers.Auth; + +public class RefreshTokenHandlerTests +{ + private readonly IJwtService _jwtService; + private readonly UserManager _userManager; + private readonly IRolePermissionService _rolePermissionService; + private readonly IAuthDataService _authData; + private readonly ILogger _logger; + private readonly RefreshTokenHandler _handler; + + public RefreshTokenHandlerTests() + { + var userStore = Substitute.For>(); + _jwtService = Substitute.For(); + var identityOptions = Microsoft.Extensions.Options.Options.Create(new IdentityOptions()); + _userManager = Substitute.For>(userStore, identityOptions, null!, null!, null!, null!, null!, null!, null!); + _rolePermissionService = Substitute.For(); + _authData = Substitute.For(); + _logger = Substitute.For>(); + _handler = new RefreshTokenHandler(_jwtService, _userManager, _rolePermissionService, _authData, _logger); + } + + [Fact] + public async Task Refresh_with_valid_token_should_return_new_tokens() + { + var user = new AppUser { Id = Guid.NewGuid(), UserName = "test@test.com", DisplayName = "Test" }; + var principal = new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()), new Claim("jti", "token-id")])); + _jwtService.ValidateRefreshToken("valid-token").Returns(principal); + _authData.IsRefreshTokenRevokedAsync("token-id", Arg.Any()).Returns(false); + _userManager.FindByIdAsync(user.Id.ToString()).Returns(user); + _userManager.GetRolesAsync(user).Returns(["Viewer"]); + _jwtService.GenerateAccessToken(user, Arg.Any>(), Arg.Any>()) + .Returns(("new-access-token", DateTime.UtcNow.AddHours(1))); + _jwtService.GenerateRefreshToken(user).Returns(("new-refresh-token", DateTime.UtcNow.AddDays(7))); + _rolePermissionService.GetPermissionsForRoles(Arg.Any>()).Returns([]); + + var result = await _handler.Handle(new RefreshTokenCommand("valid-token"), CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + result.Data!.AccessToken.ShouldBe("new-access-token"); + } + + [Fact] + public async Task Refresh_with_invalid_token_should_return_unauthorized() + { + _jwtService.ValidateRefreshToken("bad-token").Returns((ClaimsPrincipal?)null); + + var result = await _handler.Handle(new RefreshTokenCommand("bad-token"), CancellationToken.None); + + result.IsSuccess.ShouldBeFalse(); + result.StatusCode.ShouldBe(401); + } + + [Fact] + public async Task Refresh_with_revoked_token_should_return_unauthorized() + { + var principal = new ClaimsPrincipal(new ClaimsIdentity([new Claim("jti", "revoked-token-id")])); + _jwtService.ValidateRefreshToken("revoked-token").Returns(principal); + _authData.IsRefreshTokenRevokedAsync("revoked-token-id", Arg.Any()).Returns(true); + + var result = await _handler.Handle(new RefreshTokenCommand("revoked-token"), CancellationToken.None); + + result.IsSuccess.ShouldBeFalse(); + result.StatusCode.ShouldBe(401); + } + + [Fact] + public async Task Refresh_with_deleted_user_should_return_unauthorized() + { + var userId = Guid.NewGuid(); + var principal = new ClaimsPrincipal(new ClaimsIdentity([ + new Claim(ClaimTypes.NameIdentifier, userId.ToString()), new Claim("jti", "token-id")])); + _jwtService.ValidateRefreshToken("token").Returns(principal); + _authData.IsRefreshTokenRevokedAsync("token-id", Arg.Any()).Returns(false); + _userManager.FindByIdAsync(userId.ToString()).Returns((AppUser?)null); + + var result = await _handler.Handle(new RefreshTokenCommand("token"), CancellationToken.None); + + result.IsSuccess.ShouldBeFalse(); + result.StatusCode.ShouldBe(401); + } +} diff --git a/tests/Heimdall.Application.Tests/Handlers/Auth/RegisterAdminHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Auth/RegisterAdminHandlerTests.cs new file mode 100644 index 0000000..279c20e --- /dev/null +++ b/tests/Heimdall.Application.Tests/Handlers/Auth/RegisterAdminHandlerTests.cs @@ -0,0 +1,74 @@ +using Heimdall.Application.Auth.Commands.RegisterAdmin; +using Heimdall.Application.DTOs; +using Heimdall.Application.Services; +using Heimdall.Domain.Entities; +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.Logging; +using NSubstitute; + +namespace Heimdall.Application.Tests.Handlers.Auth; + +public class RegisterAdminHandlerTests +{ + private readonly UserManager _userManager; + private readonly IJwtService _jwtService; + private readonly IRolePermissionService _rolePermissionService; + private readonly ILogger _logger; + private readonly RegisterAdminHandler _handler; + + public RegisterAdminHandlerTests() + { + var userStore = Substitute.For>(); + var identityOptions = Microsoft.Extensions.Options.Options.Create(new IdentityOptions()); + _userManager = Substitute.For>(userStore, identityOptions, null!, null!, null!, null!, null!, null!, null!); + _jwtService = Substitute.For(); + _rolePermissionService = Substitute.For(); + _logger = Substitute.For>(); + _handler = new RegisterAdminHandler(_userManager, _jwtService, _rolePermissionService, _logger); + } + + [Fact] + public async Task Register_admin_should_create_user_with_admin_role() + { + _userManager.FindByEmailAsync("admin@test.com").Returns((AppUser?)null); + _userManager.CreateAsync(Arg.Any(), "password").Returns(IdentityResult.Success); + _userManager.AddToRoleAsync(Arg.Any(), Arg.Any()).Returns(IdentityResult.Success); + _userManager.GetRolesAsync(Arg.Any()).Returns(["Admin"]); + _jwtService.GenerateAccessToken(Arg.Any(), Arg.Any>(), Arg.Any>()) + .Returns(("access-token", DateTime.UtcNow.AddHours(1))); + _jwtService.GenerateRefreshToken(Arg.Any()).Returns(("refresh-token", DateTime.UtcNow.AddDays(7))); + _rolePermissionService.GetPermissionsForRoles(Arg.Any>()).Returns([]); + + var result = await _handler.Handle( + new RegisterAdminCommand("admin@test.com", "password", "Admin"), CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + await _userManager.Received(1).AddToRoleAsync(Arg.Any(), "Admin"); + } + + [Fact] + public async Task Register_admin_with_existing_email_should_return_conflict() + { + _userManager.FindByEmailAsync("existing@test.com").Returns(new AppUser()); + + var result = await _handler.Handle( + new RegisterAdminCommand("existing@test.com", "password", "Existing"), CancellationToken.None); + + result.IsSuccess.ShouldBeFalse(); + result.StatusCode.ShouldBe(409); + } + + [Fact] + public async Task Register_admin_when_creation_fails_should_return_error() + { + _userManager.FindByEmailAsync("fail@test.com").Returns((AppUser?)null); + _userManager.CreateAsync(Arg.Any(), Arg.Any()) + .Returns(IdentityResult.Failed(new IdentityError { Description = "Password too weak" })); + + var result = await _handler.Handle( + new RegisterAdminCommand("fail@test.com", "weak", "Fail"), CancellationToken.None); + + result.IsSuccess.ShouldBeFalse(); + result.Error!.ShouldContain("Password too weak"); + } +} diff --git a/tests/Heimdall.Application.Tests/Handlers/Auth/RegisterHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Auth/RegisterHandlerTests.cs new file mode 100644 index 0000000..2b128d8 --- /dev/null +++ b/tests/Heimdall.Application.Tests/Handlers/Auth/RegisterHandlerTests.cs @@ -0,0 +1,100 @@ +using Heimdall.Application.Auth.Commands.Register; +using Heimdall.Application.DTOs; +using Heimdall.Application.Services; +using Heimdall.Domain.Entities; +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.Logging; +using NSubstitute; + +namespace Heimdall.Application.Tests.Handlers.Auth; + +public class RegisterHandlerTests +{ + private readonly UserManager _userManager; + private readonly IJwtService _jwtService; + private readonly IRolePermissionService _rolePermissionService; + private readonly IAuthDataService _authData; + private readonly ILogger _logger; + private readonly RegisterHandler _handler; + + public RegisterHandlerTests() + { + var userStore = Substitute.For>(); + var identityOptions = Microsoft.Extensions.Options.Options.Create(new IdentityOptions()); + _userManager = Substitute.For>(userStore, identityOptions, null!, null!, null!, null!, null!, null!, null!); + _jwtService = Substitute.For(); + _rolePermissionService = Substitute.For(); + _authData = Substitute.For(); + _logger = Substitute.For>(); + _handler = new RegisterHandler(_userManager, _jwtService, _rolePermissionService, _authData, _logger); + } + + [Fact] + public async Task Register_with_existing_email_should_return_conflict() + { + _userManager.FindByEmailAsync("existing@test.com").Returns(new AppUser()); + + var result = await _handler.Handle( + new RegisterCommand("existing@test.com", "password", "Existing"), CancellationToken.None); + + result.IsSuccess.ShouldBeFalse(); + result.StatusCode.ShouldBe(409); + } + + [Fact] + public async Task Register_as_first_user_should_create_admin() + { + _userManager.FindByEmailAsync("first@test.com").Returns((AppUser?)null); + _authData.IsFirstUserAsync(Arg.Any()).Returns(false); + _userManager.CreateAsync(Arg.Any(), "password") + .Returns(IdentityResult.Success); + _userManager.GetRolesAsync(Arg.Any()).Returns(["Admin"]); + _jwtService.GenerateAccessToken(Arg.Any(), Arg.Any>(), Arg.Any>()) + .Returns(("access-token", DateTime.UtcNow.AddHours(1))); + _jwtService.GenerateRefreshToken(Arg.Any()).Returns(("refresh-token", DateTime.UtcNow.AddDays(7))); + _rolePermissionService.GetPermissionsForRoles(Arg.Any>()).Returns([]); + + var result = await _handler.Handle( + new RegisterCommand("first@test.com", "password", "First User"), CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + await _userManager.Received(1).AddToRoleAsync(Arg.Any(), "Admin"); + } + + [Fact] + public async Task Register_when_public_registration_disabled_should_return_403() + { + _userManager.FindByEmailAsync("user@test.com").Returns((AppUser?)null); + _authData.IsFirstUserAsync(Arg.Any()).Returns(true); + _authData.GetSettingValueAsync("auth.public-registration.enabled", Arg.Any()) + .Returns("false"); + + var result = await _handler.Handle( + new RegisterCommand("user@test.com", "password", "User"), CancellationToken.None); + + result.IsSuccess.ShouldBeFalse(); + result.StatusCode.ShouldBe(403); + } + + [Fact] + public async Task Register_when_public_registration_enabled_should_create_viewer() + { + _userManager.FindByEmailAsync("user@test.com").Returns((AppUser?)null); + _authData.IsFirstUserAsync(Arg.Any()).Returns(true); + _authData.GetSettingValueAsync("auth.public-registration.enabled", Arg.Any()) + .Returns("true"); + _userManager.CreateAsync(Arg.Any(), "password") + .Returns(IdentityResult.Success); + _userManager.GetRolesAsync(Arg.Any()).Returns(["Viewer"]); + _jwtService.GenerateAccessToken(Arg.Any(), Arg.Any>(), Arg.Any>()) + .Returns(("access-token", DateTime.UtcNow.AddHours(1))); + _jwtService.GenerateRefreshToken(Arg.Any()).Returns(("refresh-token", DateTime.UtcNow.AddDays(7))); + _rolePermissionService.GetPermissionsForRoles(Arg.Any>()).Returns([]); + + var result = await _handler.Handle( + new RegisterCommand("user@test.com", "password", "User"), CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + await _userManager.Received(1).AddToRoleAsync(Arg.Any(), "Viewer"); + } +} diff --git a/tests/Heimdall.Application.Tests/Handlers/Cameras/CreateCameraHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Cameras/CreateCameraHandlerTests.cs new file mode 100644 index 0000000..078678b --- /dev/null +++ b/tests/Heimdall.Application.Tests/Handlers/Cameras/CreateCameraHandlerTests.cs @@ -0,0 +1,57 @@ +using Heimdall.Application.Cameras.Commands.CreateCamera; +using Heimdall.Application.Common; +using Heimdall.Application.Tests.Common; +using Heimdall.Domain.Entities; +using NSubstitute; + +namespace Heimdall.Application.Tests.Handlers.Cameras; + +public class CreateCameraHandlerTests +{ + private readonly Site _existingSite = new("Test Site", "Paris", "Europe/Paris"); + + [Fact] + public async Task Create_camera_should_return_success() + { + var context = Substitute.For(); + context.Sites.Returns(MockDbSetHelper.CreateFor([_existingSite])); + context.Cameras.Returns(MockDbSetHelper.CreateFor()); + var handler = new CreateCameraCommandHandler(context); + var command = new CreateCameraCommand(_existingSite.Id, "Front Door", "rtsp://192.168.1.100/stream1", "Hikvision", "DS-2CD2T47G2-L"); + + var result = await handler.Handle(command, CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + result.Data.ShouldNotBeNull(); + result.Data.Name.ShouldBe("Front Door"); + result.Data.SiteId.ShouldBe(_existingSite.Id); + } + + [Fact] + public async Task Create_camera_nonexistent_site_should_return_not_found() + { + var context = Substitute.For(); + context.Sites.Returns(MockDbSetHelper.CreateFor([_existingSite])); + var handler = new CreateCameraCommandHandler(context); + var command = new CreateCameraCommand(Guid.NewGuid(), "Camera", null, null, null); + + var result = await handler.Handle(command, CancellationToken.None); + + result.IsSuccess.ShouldBeFalse(); + result.StatusCode.ShouldBe(404); + } + + [Fact] + public async Task Create_camera_should_add_and_save() + { + var context = Substitute.For(); + context.Sites.Returns(MockDbSetHelper.CreateFor([_existingSite])); + context.Cameras.Returns(MockDbSetHelper.CreateFor()); + var handler = new CreateCameraCommandHandler(context); + var command = new CreateCameraCommand(_existingSite.Id, "Back Yard", null, null, null); + + await handler.Handle(command, CancellationToken.None); + + await context.Received(1).SaveChangesAsync(Arg.Any()); + } +} diff --git a/tests/Heimdall.Application.Tests/Handlers/Cameras/DeleteCameraHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Cameras/DeleteCameraHandlerTests.cs new file mode 100644 index 0000000..e6c3f96 --- /dev/null +++ b/tests/Heimdall.Application.Tests/Handlers/Cameras/DeleteCameraHandlerTests.cs @@ -0,0 +1,54 @@ +using Heimdall.Application.Cameras.Commands.DeleteCamera; +using Heimdall.Application.Common; +using Heimdall.Application.Tests.Common; +using Heimdall.Domain.Entities; +using NSubstitute; + +namespace Heimdall.Application.Tests.Handlers.Cameras; + +public class DeleteCameraHandlerTests +{ + private readonly Camera _existingCamera = new(Guid.NewGuid(), "Front Door"); + + [Fact] + public async Task Delete_camera_should_return_success() + { + var context = Substitute.For(); + context.Cameras.Returns(MockDbSetHelper.CreateFor([_existingCamera])); + var handler = new DeleteCameraCommandHandler(context); + var command = new DeleteCameraCommand(_existingCamera.Id); + + var result = await handler.Handle(command, CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + } + + [Fact] + public async Task Delete_nonexistent_camera_should_return_not_found() + { + var context = Substitute.For(); + context.Cameras.Returns(MockDbSetHelper.CreateFor([_existingCamera])); + var handler = new DeleteCameraCommandHandler(context); + var command = new DeleteCameraCommand(Guid.NewGuid()); + + var result = await handler.Handle(command, CancellationToken.None); + + result.IsSuccess.ShouldBeFalse(); + result.StatusCode.ShouldBe(404); + } + + [Fact] + public async Task Delete_camera_should_soft_delete_and_save() + { + var context = Substitute.For(); + context.Cameras.Returns(MockDbSetHelper.CreateFor([_existingCamera])); + var handler = new DeleteCameraCommandHandler(context); + var command = new DeleteCameraCommand(_existingCamera.Id); + + await handler.Handle(command, CancellationToken.None); + + _existingCamera.IsDeleted.ShouldBeTrue(); + _existingCamera.DeletedAt.ShouldNotBeNull(); + await context.Received(1).SaveChangesAsync(Arg.Any()); + } +} diff --git a/tests/Heimdall.Application.Tests/Handlers/Cameras/GetCameraHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Cameras/GetCameraHandlerTests.cs new file mode 100644 index 0000000..4bc8066 --- /dev/null +++ b/tests/Heimdall.Application.Tests/Handlers/Cameras/GetCameraHandlerTests.cs @@ -0,0 +1,42 @@ +using Heimdall.Application.Cameras.Queries.GetCamera; +using Heimdall.Application.Common; +using Heimdall.Application.Tests.Common; +using Heimdall.Domain.Entities; +using NSubstitute; + +namespace Heimdall.Application.Tests.Handlers.Cameras; + +public class GetCameraHandlerTests +{ + private readonly Camera _existingCamera = new(Guid.NewGuid(), "Front Door", "rtsp://192.168.1.100/stream1", "Hikvision"); + + [Fact] + public async Task Get_camera_should_return_camera() + { + var context = Substitute.For(); + context.Cameras.Returns(MockDbSetHelper.CreateFor([_existingCamera])); + var handler = new GetCameraQueryHandler(context); + var query = new GetCameraQuery(_existingCamera.Id); + + var result = await handler.Handle(query, CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + result.Data.ShouldNotBeNull(); + result.Data.Name.ShouldBe("Front Door"); + result.Data.Manufacturer.ShouldBe("Hikvision"); + } + + [Fact] + public async Task Get_nonexistent_camera_should_return_not_found() + { + var context = Substitute.For(); + context.Cameras.Returns(MockDbSetHelper.CreateFor([_existingCamera])); + var handler = new GetCameraQueryHandler(context); + var query = new GetCameraQuery(Guid.NewGuid()); + + var result = await handler.Handle(query, CancellationToken.None); + + result.IsSuccess.ShouldBeFalse(); + result.StatusCode.ShouldBe(404); + } +} diff --git a/tests/Heimdall.Application.Tests/Handlers/Cameras/GetCamerasBySiteHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Cameras/GetCamerasBySiteHandlerTests.cs new file mode 100644 index 0000000..685f5fe --- /dev/null +++ b/tests/Heimdall.Application.Tests/Handlers/Cameras/GetCamerasBySiteHandlerTests.cs @@ -0,0 +1,83 @@ +using Heimdall.Application.Cameras.Queries.GetCamerasBySite; +using Heimdall.Application.Common; +using Heimdall.Application.Tests.Common; +using Heimdall.Domain.Entities; +using NSubstitute; + +namespace Heimdall.Application.Tests.Handlers.Cameras; + +public class GetCamerasBySiteHandlerTests +{ + private readonly Guid _siteId = Guid.NewGuid(); + private readonly Guid _otherSiteId = Guid.NewGuid(); + private readonly List _cameras; + + public GetCamerasBySiteHandlerTests() + { + _cameras = + [ + new Camera(_siteId, "Back Yard", "rtsp://192.168.1.102/stream1"), + new Camera(_siteId, "Front Door", "rtsp://192.168.1.100/stream1"), + new Camera(_otherSiteId, "Other Camera", "rtsp://10.0.0.1/stream1"), + ]; + } + + [Fact] + public async Task Get_cameras_by_site_should_return_site_cameras() + { + var context = Substitute.For(); + context.Cameras.Returns(MockDbSetHelper.CreateFor(_cameras)); + var handler = new GetCamerasBySiteQueryHandler(context); + var query = new GetCamerasBySiteQuery(_siteId, Page: 1, PageSize: 20); + + var result = await handler.Handle(query, CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + result.Data.ShouldNotBeNull(); + result.Data.Items.Count.ShouldBe(2); + result.Data.TotalCount.ShouldBe(2); + } + + [Fact] + public async Task Get_cameras_by_site_should_order_by_name() + { + var context = Substitute.For(); + context.Cameras.Returns(MockDbSetHelper.CreateFor(_cameras)); + var handler = new GetCamerasBySiteQueryHandler(context); + var query = new GetCamerasBySiteQuery(_siteId, Page: 1, PageSize: 20); + + var result = await handler.Handle(query, CancellationToken.None); + + result.Data!.Items[0].Name.ShouldBe("Back Yard"); + result.Data.Items[1].Name.ShouldBe("Front Door"); + } + + [Fact] + public async Task Get_cameras_by_site_should_return_empty_for_site_with_no_cameras() + { + var context = Substitute.For(); + context.Cameras.Returns(MockDbSetHelper.CreateFor(_cameras)); + var handler = new GetCamerasBySiteQueryHandler(context); + var query = new GetCamerasBySiteQuery(Guid.NewGuid(), Page: 1, PageSize: 20); + + var result = await handler.Handle(query, CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + result.Data!.Items.ShouldBeEmpty(); + result.Data.TotalCount.ShouldBe(0); + } + + [Fact] + public async Task Get_cameras_by_site_should_respect_pagination() + { + var context = Substitute.For(); + context.Cameras.Returns(MockDbSetHelper.CreateFor(_cameras)); + var handler = new GetCamerasBySiteQueryHandler(context); + var query = new GetCamerasBySiteQuery(_siteId, Page: 1, PageSize: 1); + + var result = await handler.Handle(query, CancellationToken.None); + + result.Data!.Items.Count.ShouldBe(1); + result.Data.TotalCount.ShouldBe(2); + } +} diff --git a/tests/Heimdall.Application.Tests/Handlers/Cameras/SetCameraCredentialsHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Cameras/SetCameraCredentialsHandlerTests.cs new file mode 100644 index 0000000..6119a2d --- /dev/null +++ b/tests/Heimdall.Application.Tests/Handlers/Cameras/SetCameraCredentialsHandlerTests.cs @@ -0,0 +1,77 @@ +using Heimdall.Application.Cameras.Commands.SetCredentials; +using Heimdall.Application.Common; +using Heimdall.Application.Tests.Common; +using Heimdall.Domain.Entities; +using NSubstitute; + +namespace Heimdall.Application.Tests.Handlers.Cameras; + +public class SetCameraCredentialsHandlerTests +{ + private readonly Camera _existingCamera = new(Guid.NewGuid(), "Front Door"); + + [Fact] + public async Task Set_credentials_should_return_success() + { + var protector = Substitute.For(); + protector.Encrypt(Arg.Any()).Returns(c => $"enc_{c.Arg()}"); + + var context = Substitute.For(); + context.Cameras.Returns(MockDbSetHelper.CreateFor([_existingCamera])); + var handler = new SetCameraCredentialsCommandHandler(context, protector); + var command = new SetCameraCredentialsCommand(_existingCamera.Id, "admin", "pass123", "rtsp_user", "rtsp_pass"); + + var result = await handler.Handle(command, CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + } + + [Fact] + public async Task Set_credentials_nonexistent_camera_should_return_not_found() + { + var protector = Substitute.For(); + var context = Substitute.For(); + context.Cameras.Returns(MockDbSetHelper.CreateFor([_existingCamera])); + var handler = new SetCameraCredentialsCommandHandler(context, protector); + var command = new SetCameraCredentialsCommand(Guid.NewGuid(), "admin", "pass", "user", "pass"); + + var result = await handler.Handle(command, CancellationToken.None); + + result.IsSuccess.ShouldBeFalse(); + result.StatusCode.ShouldBe(404); + } + + [Fact] + public async Task Set_credentials_should_encrypt_sensitive_fields() + { + var protector = Substitute.For(); + protector.Encrypt(Arg.Any()).Returns(c => $"enc_{c.Arg()}"); + + var context = Substitute.For(); + context.Cameras.Returns(MockDbSetHelper.CreateFor([_existingCamera])); + var handler = new SetCameraCredentialsCommandHandler(context, protector); + var command = new SetCameraCredentialsCommand(_existingCamera.Id, "admin", "secret_pwd", "rtsp_user", "rtsp_secret"); + + await handler.Handle(command, CancellationToken.None); + + protector.Received(1).Encrypt("secret_pwd"); + protector.Received(1).Encrypt("rtsp_user"); + protector.Received(1).Encrypt("rtsp_secret"); + } + + [Fact] + public async Task Set_credentials_should_save_changes() + { + var protector = Substitute.For(); + protector.Encrypt(Arg.Any()).Returns(c => $"enc_{c.Arg()}"); + + var context = Substitute.For(); + context.Cameras.Returns(MockDbSetHelper.CreateFor([_existingCamera])); + var handler = new SetCameraCredentialsCommandHandler(context, protector); + var command = new SetCameraCredentialsCommand(_existingCamera.Id, "admin", "pass", "user", "pass"); + + await handler.Handle(command, CancellationToken.None); + + await context.Received(1).SaveChangesAsync(Arg.Any()); + } +} diff --git a/tests/Heimdall.Application.Tests/Handlers/Cameras/UpdateCameraHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Cameras/UpdateCameraHandlerTests.cs new file mode 100644 index 0000000..b5015f2 --- /dev/null +++ b/tests/Heimdall.Application.Tests/Handlers/Cameras/UpdateCameraHandlerTests.cs @@ -0,0 +1,70 @@ +using Heimdall.Application.Cameras.Commands.UpdateCamera; +using Heimdall.Application.Common; +using Heimdall.Application.Tests.Common; +using Heimdall.Domain.Entities; +using Heimdall.Domain.Enums; +using NSubstitute; + +namespace Heimdall.Application.Tests.Handlers.Cameras; + +public class UpdateCameraHandlerTests +{ + private readonly Camera _existingCamera = new(Guid.NewGuid(), "Front Door", "rtsp://192.168.1.100/stream1", "Hikvision", "DS-2CD2T47G2-L"); + + [Fact] + public async Task Update_camera_should_return_success() + { + var context = Substitute.For(); + context.Cameras.Returns(MockDbSetHelper.CreateFor([_existingCamera])); + var handler = new UpdateCameraCommandHandler(context); + var command = new UpdateCameraCommand(_existingCamera.Id, "Rear Door", "rtsp://192.168.1.101/stream1", CameraStatus.Online, "Dahua", "IPC-HFW5442T-ZE"); + + var result = await handler.Handle(command, CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + result.Data.ShouldNotBeNull(); + result.Data.Name.ShouldBe("Rear Door"); + result.Data.Status.ShouldBe(CameraStatus.Online); + } + + [Fact] + public async Task Update_nonexistent_camera_should_return_not_found() + { + var context = Substitute.For(); + context.Cameras.Returns(MockDbSetHelper.CreateFor([_existingCamera])); + var handler = new UpdateCameraCommandHandler(context); + var command = new UpdateCameraCommand(Guid.NewGuid(), "Name", null, null); + + var result = await handler.Handle(command, CancellationToken.None); + + result.IsSuccess.ShouldBeFalse(); + result.StatusCode.ShouldBe(404); + } + + [Fact] + public async Task Update_camera_without_status_should_not_change_status() + { + var context = Substitute.For(); + context.Cameras.Returns(MockDbSetHelper.CreateFor([_existingCamera])); + var handler = new UpdateCameraCommandHandler(context); + var command = new UpdateCameraCommand(_existingCamera.Id, "Renamed", null, null); + + await handler.Handle(command, CancellationToken.None); + + _existingCamera.Name.ShouldBe("Renamed"); + _existingCamera.Status.ShouldBe(CameraStatus.Disabled); + } + + [Fact] + public async Task Update_camera_should_save_changes() + { + var context = Substitute.For(); + context.Cameras.Returns(MockDbSetHelper.CreateFor([_existingCamera])); + var handler = new UpdateCameraCommandHandler(context); + var command = new UpdateCameraCommand(_existingCamera.Id, "Name", null, null); + + await handler.Handle(command, CancellationToken.None); + + await context.Received(1).SaveChangesAsync(Arg.Any()); + } +} diff --git a/tests/Heimdall.Application.Tests/Handlers/Events/AttachSnapshotHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Events/AttachSnapshotHandlerTests.cs new file mode 100644 index 0000000..2e1371f --- /dev/null +++ b/tests/Heimdall.Application.Tests/Handlers/Events/AttachSnapshotHandlerTests.cs @@ -0,0 +1,41 @@ +using Heimdall.Application.Common; +using Heimdall.Application.Events.Commands.AttachSnapshot; +using Heimdall.Application.Tests.Common; +using Heimdall.Domain.Entities; +using Heimdall.Domain.Enums; +using NSubstitute; + +namespace Heimdall.Application.Tests.Handlers.Events; + +public class AttachSnapshotHandlerTests +{ + [Fact] + public async Task Attach_snapshot_should_return_success() + { + var ev = new CameraEvent(Guid.NewGuid(), EventType.MotionDetected, 0.9); + var context = Substitute.For(); + context.CameraEvents.Returns(MockDbSetHelper.CreateFor([ev])); + context.SaveChangesWithRetryAsync(Arg.Any(), Arg.Any()).Returns(Task.CompletedTask); + var handler = new AttachSnapshotHandler(context); + + var result = await handler.Handle( + new AttachSnapshotCommand(ev.Id, "https://example.com/snapshot.jpg", "https://example.com/thumb.jpg"), + CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + } + + [Fact] + public async Task Attach_snapshot_to_unknown_event_should_return_not_found() + { + var context = Substitute.For(); + context.CameraEvents.Returns(MockDbSetHelper.CreateFor()); + var handler = new AttachSnapshotHandler(context); + + var result = await handler.Handle( + new AttachSnapshotCommand(Guid.NewGuid(), "snap.jpg", null), CancellationToken.None); + + result.IsSuccess.ShouldBeFalse(); + result.StatusCode.ShouldBe(404); + } +} diff --git a/tests/Heimdall.Application.Tests/Handlers/Events/CreateEventHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Events/CreateEventHandlerTests.cs new file mode 100644 index 0000000..99ffd9f --- /dev/null +++ b/tests/Heimdall.Application.Tests/Handlers/Events/CreateEventHandlerTests.cs @@ -0,0 +1,67 @@ +using Heimdall.Application.Common; +using Heimdall.Application.Events.Commands.CreateEvent; +using Heimdall.Application.Events.Notifications; +using Heimdall.Application.Tests.Common; +using Heimdall.Domain.Entities; +using Heimdall.Domain.Enums; +using MediatR; +using NSubstitute; + +namespace Heimdall.Application.Tests.Handlers.Events; + +public class CreateEventHandlerTests +{ + private readonly IApplicationDbContext _context; + private readonly IPublisher _publisher; + private readonly CreateEventHandler _handler; + + public CreateEventHandlerTests() + { + _context = Substitute.For(); + _publisher = Substitute.For(); + _handler = new CreateEventHandler(_context, _publisher); + } + + [Fact] + public async Task Create_event_should_return_success_and_publish_notification() + { + var site = new Site("Test", "Paris", "Europe/Paris"); + var camera = new Camera(site.Id, "Cam-1"); + var cameraId = camera.Id; + var occuredAt = DateTime.UtcNow; + + _context.Cameras.Returns(MockDbSetHelper.CreateFor([camera])); + var cameraEventsDb = new CameraAwareDbSet([], id => id == cameraId ? camera : null); + _context.CameraEvents.Returns(cameraEventsDb); + _context.SaveChangesWithRetryAsync(Arg.Any(), Arg.Any()).Returns(Task.CompletedTask); + + var command = new CreateEventCommand(cameraId, EventType.MotionDetected, 0.95, null, null, occuredAt); + + var result = await _handler.Handle(command, CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + result.Data.ShouldNotBeNull(); + var data = result.Data!; + data.CameraId.ShouldBe(cameraId); + data.Type.ShouldBe(EventType.MotionDetected); + + var eventId = result.Data!.Id; +#pragma warning disable CS8602 + await _publisher.Received(1).Publish(Arg.Is(n => n.Event.Id == eventId), Arg.Any()); +#pragma warning restore CS8602 + } + + [Fact] + public async Task Create_event_with_unknown_camera_should_return_not_found() + { + var unknownId = Guid.NewGuid(); + _context.Cameras.FindAsync([unknownId], Arg.Any()).Returns((Camera?)null); + + var result = await _handler.Handle( + new CreateEventCommand(unknownId, EventType.MotionDetected, 0.9, null, null, null), + CancellationToken.None); + + result.IsSuccess.ShouldBeFalse(); + result.StatusCode.ShouldBe(404); + } +} diff --git a/tests/Heimdall.Application.Tests/Handlers/Events/DeleteEventHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Events/DeleteEventHandlerTests.cs new file mode 100644 index 0000000..939eead --- /dev/null +++ b/tests/Heimdall.Application.Tests/Handlers/Events/DeleteEventHandlerTests.cs @@ -0,0 +1,38 @@ +using Heimdall.Application.Common; +using Heimdall.Application.Events.Commands.DeleteEvent; +using Heimdall.Application.Tests.Common; +using Heimdall.Domain.Entities; +using Heimdall.Domain.Enums; +using NSubstitute; + +namespace Heimdall.Application.Tests.Handlers.Events; + +public class DeleteEventHandlerTests +{ + [Fact] + public async Task Delete_event_should_return_success() + { + var ev = new CameraEvent(Guid.NewGuid(), EventType.MotionDetected, 0.9); + var context = Substitute.For(); + context.CameraEvents.Returns(MockDbSetHelper.CreateFor([ev])); + context.SaveChangesWithRetryAsync(Arg.Any(), Arg.Any()).Returns(Task.CompletedTask); + var handler = new DeleteEventHandler(context); + + var result = await handler.Handle(new DeleteEventCommand(ev.Id), CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + } + + [Fact] + public async Task Delete_unknown_event_should_return_not_found() + { + var context = Substitute.For(); + context.CameraEvents.Returns(MockDbSetHelper.CreateFor()); + var handler = new DeleteEventHandler(context); + + var result = await handler.Handle(new DeleteEventCommand(Guid.NewGuid()), CancellationToken.None); + + result.IsSuccess.ShouldBeFalse(); + result.StatusCode.ShouldBe(404); + } +} diff --git a/tests/Heimdall.Application.Tests/Handlers/Events/GetEventHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Events/GetEventHandlerTests.cs new file mode 100644 index 0000000..91ea1a5 --- /dev/null +++ b/tests/Heimdall.Application.Tests/Handlers/Events/GetEventHandlerTests.cs @@ -0,0 +1,44 @@ +using Heimdall.Application.Common; +using Heimdall.Application.Events.Queries.GetEvent; +using Heimdall.Application.Tests.Common; +using Heimdall.Domain.Entities; +using Heimdall.Domain.Enums; +using NSubstitute; + +namespace Heimdall.Application.Tests.Handlers.Events; + +public class GetEventHandlerTests +{ + [Fact] + public async Task Get_event_should_return_event_when_found() + { + var site = new Site("Test", "Paris", "Europe/Paris"); + var camera = new Camera(site.Id, "Cam-1"); + var ev = new CameraEvent(camera.Id, EventType.MotionDetected, 0.95, DateTime.UtcNow); + ev.SetCamera(camera); + + var context = Substitute.For(); + context.CameraEvents.Returns(MockDbSetHelper.CreateFor([ev])); + var handler = new GetEventHandler(context); + + var result = await handler.Handle(new GetEventQuery(ev.Id), CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + result.Data.ShouldNotBeNull(); + result.Data.Id.ShouldBe(ev.Id); + result.Data.CameraId.ShouldBe(camera.Id); + } + + [Fact] + public async Task Get_event_should_return_not_found_when_missing() + { + var context = Substitute.For(); + context.CameraEvents.Returns(MockDbSetHelper.CreateFor()); + var handler = new GetEventHandler(context); + + var result = await handler.Handle(new GetEventQuery(Guid.NewGuid()), CancellationToken.None); + + result.IsSuccess.ShouldBeFalse(); + result.StatusCode.ShouldBe(404); + } +} diff --git a/tests/Heimdall.Application.Tests/Handlers/Events/GetEventsHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Events/GetEventsHandlerTests.cs new file mode 100644 index 0000000..8538a23 --- /dev/null +++ b/tests/Heimdall.Application.Tests/Handlers/Events/GetEventsHandlerTests.cs @@ -0,0 +1,60 @@ +using Heimdall.Application.Common; +using Heimdall.Application.Events.Queries.GetEvents; +using Heimdall.Application.Tests.Common; +using Heimdall.Domain.Entities; +using Heimdall.Domain.Enums; +using NSubstitute; + +namespace Heimdall.Application.Tests.Handlers.Events; + +public class GetEventsHandlerTests +{ + [Fact] + public async Task Get_events_should_return_paged_results() + { + var site = new Site("Test", "Paris", "Europe/Paris"); + var camera = new Camera(site.Id, "Cam-1"); + var events = new List + { + new(camera.Id, EventType.MotionDetected, 0.95, DateTime.UtcNow.AddMinutes(-5)), + new(camera.Id, EventType.PersonDetected, 0.85, DateTime.UtcNow.AddMinutes(-10)), + }; + foreach (var e in events) e.SetCamera(camera); + + var context = Substitute.For(); + context.CameraEvents.Returns(MockDbSetHelper.CreateFor(events)); + var handler = new GetEventsHandler(context); + + var result = await handler.Handle(new GetEventsQuery(null, null, null, null, null, null, 1, 50), CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + result.Data.ShouldNotBeNull(); + result.Data.Items.Count.ShouldBe(2); + result.Data.TotalCount.ShouldBe(2); + } + + [Fact] + public async Task Get_events_should_filter_by_camera_id() + { + var site = new Site("Test", "Paris", "Europe/Paris"); + var camera1 = new Camera(site.Id, "Cam-1"); + var camera2 = new Camera(site.Id, "Cam-2"); + var events = new List + { + new(camera1.Id, EventType.MotionDetected, 0.9, DateTime.UtcNow), + new(camera2.Id, EventType.PersonDetected, 0.8, DateTime.UtcNow), + }; + events[0].SetCamera(camera1); + events[1].SetCamera(camera2); + + var context = Substitute.For(); + context.CameraEvents.Returns(MockDbSetHelper.CreateFor(events)); + var handler = new GetEventsHandler(context); + + var result = await handler.Handle(new GetEventsQuery(camera1.Id, null, null, null, null, null, 1, 50), CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + result.Data!.Items.Count.ShouldBe(1); + result.Data.Items[0].CameraId.ShouldBe(camera1.Id); + } +} diff --git a/tests/Heimdall.Application.Tests/Handlers/Events/GetRecentByCameraHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Events/GetRecentByCameraHandlerTests.cs new file mode 100644 index 0000000..cbc51db --- /dev/null +++ b/tests/Heimdall.Application.Tests/Handlers/Events/GetRecentByCameraHandlerTests.cs @@ -0,0 +1,51 @@ +using Heimdall.Application.Common; +using Heimdall.Application.Events.Queries.GetRecentByCamera; +using Heimdall.Application.Tests.Common; +using Heimdall.Domain.Entities; +using Heimdall.Domain.Enums; +using NSubstitute; + +namespace Heimdall.Application.Tests.Handlers.Events; + +public class GetRecentByCameraHandlerTests +{ + [Fact] + public async Task Get_recent_by_camera_should_return_events_ordered_by_occurred_at_desc() + { + var site = new Site("Test", "Paris", "Europe/Paris"); + var camera = new Camera(site.Id, "Cam-1"); + var cameraId = camera.Id; + var events = new List + { + new(cameraId, EventType.MotionDetected, 0.9, DateTime.UtcNow.AddHours(-3)), + new(cameraId, EventType.PersonDetected, 0.8, DateTime.UtcNow.AddHours(-2)), + new(cameraId, EventType.VehicleDetected, 0.7, DateTime.UtcNow.AddHours(-1)), + }; + foreach (var e in events) e.SetCamera(camera); + + var context = Substitute.For(); + context.CameraEvents.Returns(MockDbSetHelper.CreateFor(events)); + var handler = new GetRecentByCameraHandler(context); + + var result = await handler.Handle(new GetRecentByCameraQuery(cameraId, 10), CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + result.Data.ShouldNotBeNull(); + result.Data.Count.ShouldBe(3); + result.Data[0].OccurredAt.ShouldBe(events[2].OccurredAt); + } + + [Fact] + public async Task Get_recent_by_camera_with_no_events_should_return_empty() + { + var cameraId = Guid.NewGuid(); + var context = Substitute.For(); + context.CameraEvents.Returns(MockDbSetHelper.CreateFor()); + var handler = new GetRecentByCameraHandler(context); + + var result = await handler.Handle(new GetRecentByCameraQuery(cameraId, 10), CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + result.Data.ShouldBeEmpty(); + } +} diff --git a/tests/Heimdall.Application.Tests/Handlers/Settings/CreateAppSettingHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Settings/CreateAppSettingHandlerTests.cs new file mode 100644 index 0000000..4450e48 --- /dev/null +++ b/tests/Heimdall.Application.Tests/Handlers/Settings/CreateAppSettingHandlerTests.cs @@ -0,0 +1,43 @@ +using Heimdall.Application.Common; +using Heimdall.Application.Settings.Commands.CreateAppSetting; +using Heimdall.Application.Tests.Common; +using Heimdall.Domain.Entities; +using NSubstitute; + +namespace Heimdall.Application.Tests.Handlers.Settings; + +public class CreateAppSettingHandlerTests +{ + [Fact] + public async Task Create_setting_should_return_success() + { + var context = Substitute.For(); + context.AppSettings.Returns(MockDbSetHelper.CreateFor()); + context.SaveChangesWithRetryAsync(Arg.Any(), Arg.Any()).Returns(Task.CompletedTask); + var handler = new CreateAppSettingCommandHandler(context); + + var result = await handler.Handle( + new CreateAppSettingCommand("test.key", "test-value", "General", "Test description"), + CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + result.Data.ShouldNotBeNull(); + result.Data.Key.ShouldBe("test.key"); + result.Data.Value.ShouldBe("test-value"); + } + + [Fact] + public async Task Create_duplicate_setting_should_return_conflict() + { + var existing = new AppSetting("test.key", "existing-value"); + var context = Substitute.For(); + context.AppSettings.Returns(MockDbSetHelper.CreateFor([existing])); + var handler = new CreateAppSettingCommandHandler(context); + + var result = await handler.Handle( + new CreateAppSettingCommand("test.key", "new-value"), CancellationToken.None); + + result.IsSuccess.ShouldBeFalse(); + result.StatusCode.ShouldBe(409); + } +} diff --git a/tests/Heimdall.Application.Tests/Handlers/Settings/DeleteAppSettingHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Settings/DeleteAppSettingHandlerTests.cs new file mode 100644 index 0000000..8b3c9c4 --- /dev/null +++ b/tests/Heimdall.Application.Tests/Handlers/Settings/DeleteAppSettingHandlerTests.cs @@ -0,0 +1,37 @@ +using Heimdall.Application.Common; +using Heimdall.Application.Settings.Commands.DeleteAppSetting; +using Heimdall.Application.Tests.Common; +using Heimdall.Domain.Entities; +using NSubstitute; + +namespace Heimdall.Application.Tests.Handlers.Settings; + +public class DeleteAppSettingHandlerTests +{ + [Fact] + public async Task Delete_setting_should_return_success() + { + var setting = new AppSetting("test.key", "value"); + var context = Substitute.For(); + context.AppSettings.Returns(MockDbSetHelper.CreateFor([setting])); + context.SaveChangesWithRetryAsync(Arg.Any(), Arg.Any()).Returns(Task.CompletedTask); + var handler = new DeleteAppSettingCommandHandler(context); + + var result = await handler.Handle(new DeleteAppSettingCommand("test.key"), CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + } + + [Fact] + public async Task Delete_nonexistent_setting_should_return_not_found() + { + var context = Substitute.For(); + context.AppSettings.Returns(MockDbSetHelper.CreateFor()); + var handler = new DeleteAppSettingCommandHandler(context); + + var result = await handler.Handle(new DeleteAppSettingCommand("missing.key"), CancellationToken.None); + + result.IsSuccess.ShouldBeFalse(); + result.StatusCode.ShouldBe(404); + } +} diff --git a/tests/Heimdall.Application.Tests/Handlers/Settings/GetAgentSettingsHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Settings/GetAgentSettingsHandlerTests.cs new file mode 100644 index 0000000..b357f2a --- /dev/null +++ b/tests/Heimdall.Application.Tests/Handlers/Settings/GetAgentSettingsHandlerTests.cs @@ -0,0 +1,46 @@ +using Heimdall.Application.Common; +using Heimdall.Application.Settings.Queries.GetAgentSettings; +using Heimdall.Application.Tests.Common; +using Heimdall.Domain.Entities; +using NSubstitute; + +namespace Heimdall.Application.Tests.Handlers.Settings; + +public class GetAgentSettingsHandlerTests +{ + [Fact] + public async Task Get_agent_settings_should_return_settings_for_agent() + { + var agentId = Guid.NewGuid(); + var otherAgentId = Guid.NewGuid(); + var settings = new List + { + new(agentId, "key1", "value1"), + new(agentId, "key2", "value2"), + new(otherAgentId, "key3", "value3"), + }; + var context = Substitute.For(); + context.AgentSettings.Returns(MockDbSetHelper.CreateFor(settings)); + var handler = new GetAgentSettingsQueryHandler(context); + + var result = await handler.Handle(new GetAgentSettingsQuery(agentId), CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + result.Data!.Count.ShouldBe(2); + result.Data.ShouldAllBe(s => s.AgentId == agentId); + } + + [Fact] + public async Task Get_agent_settings_for_agent_with_none_should_return_empty() + { + var agentId = Guid.NewGuid(); + var context = Substitute.For(); + context.AgentSettings.Returns(MockDbSetHelper.CreateFor()); + var handler = new GetAgentSettingsQueryHandler(context); + + var result = await handler.Handle(new GetAgentSettingsQuery(agentId), CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + result.Data.ShouldBeEmpty(); + } +} diff --git a/tests/Heimdall.Application.Tests/Handlers/Settings/GetEffectiveAgentConfigHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Settings/GetEffectiveAgentConfigHandlerTests.cs new file mode 100644 index 0000000..71778cf --- /dev/null +++ b/tests/Heimdall.Application.Tests/Handlers/Settings/GetEffectiveAgentConfigHandlerTests.cs @@ -0,0 +1,38 @@ +using Heimdall.Application.Common; +using Heimdall.Application.Settings.Queries.GetEffectiveAgentConfig; +using Heimdall.Application.Tests.Common; +using Heimdall.Domain.Entities; +using NSubstitute; + +namespace Heimdall.Application.Tests.Handlers.Settings; + +public class GetEffectiveAgentConfigHandlerTests +{ + [Fact] + public async Task Get_effective_config_should_merge_app_and_agent_settings() + { + var agentId = Guid.NewGuid(); + var appSettings = new List + { + new("global.key", "global-value", "General"), + new("shared.key", "app-value", "General"), + }; + var agentSettings = new List + { + new(agentId, "shared.key", "agent-override"), + new(agentId, "agent.only", "agent-value"), + }; + var context = Substitute.For(); + context.AppSettings.Returns(MockDbSetHelper.CreateFor(appSettings)); + context.AgentSettings.Returns(MockDbSetHelper.CreateFor(agentSettings)); + var handler = new GetEffectiveAgentConfigQueryHandler(context); + + var result = await handler.Handle(new GetEffectiveAgentConfigQuery(agentId), CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + result.Data.ShouldNotBeNull(); + result.Data["global.key"].ShouldBe("global-value"); + result.Data["shared.key"].ShouldBe("agent-override"); + result.Data["agent.only"].ShouldBe("agent-value"); + } +} diff --git a/tests/Heimdall.Application.Tests/Handlers/Settings/GetSettingByKeyHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Settings/GetSettingByKeyHandlerTests.cs new file mode 100644 index 0000000..62e37a4 --- /dev/null +++ b/tests/Heimdall.Application.Tests/Handlers/Settings/GetSettingByKeyHandlerTests.cs @@ -0,0 +1,38 @@ +using Heimdall.Application.Common; +using Heimdall.Application.Settings.Queries.GetSettingByKey; +using Heimdall.Application.Tests.Common; +using Heimdall.Domain.Entities; +using NSubstitute; + +namespace Heimdall.Application.Tests.Handlers.Settings; + +public class GetSettingByKeyHandlerTests +{ + [Fact] + public async Task Get_setting_by_key_should_return_setting_when_found() + { + var setting = new AppSetting("test.key", "test-value", "General", "Test description"); + var context = Substitute.For(); + context.AppSettings.Returns(MockDbSetHelper.CreateFor([setting])); + var handler = new GetSettingByKeyQueryHandler(context); + + var result = await handler.Handle(new GetSettingByKeyQuery("test.key"), CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + result.Data!.Key.ShouldBe("test.key"); + result.Data.Value.ShouldBe("test-value"); + } + + [Fact] + public async Task Get_setting_by_unknown_key_should_return_not_found() + { + var context = Substitute.For(); + context.AppSettings.Returns(MockDbSetHelper.CreateFor()); + var handler = new GetSettingByKeyQueryHandler(context); + + var result = await handler.Handle(new GetSettingByKeyQuery("missing.key"), CancellationToken.None); + + result.IsSuccess.ShouldBeFalse(); + result.StatusCode.ShouldBe(404); + } +} diff --git a/tests/Heimdall.Application.Tests/Handlers/Settings/GetSettingsHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Settings/GetSettingsHandlerTests.cs new file mode 100644 index 0000000..dd541e6 --- /dev/null +++ b/tests/Heimdall.Application.Tests/Handlers/Settings/GetSettingsHandlerTests.cs @@ -0,0 +1,30 @@ +using Heimdall.Application.Common; +using Heimdall.Application.Settings.Queries.GetSettings; +using Heimdall.Application.Tests.Common; +using Heimdall.Domain.Entities; +using NSubstitute; + +namespace Heimdall.Application.Tests.Handlers.Settings; + +public class GetSettingsHandlerTests +{ + [Fact] + public async Task Get_settings_should_return_all_settings_ordered() + { + var settings = new List + { + new("z.key", "z-value", "ZCategory"), + new("a.key", "a-value", "ACategory"), + new("b.key", "b-value", "ACategory"), + }; + var context = Substitute.For(); + context.AppSettings.Returns(MockDbSetHelper.CreateFor(settings)); + var handler = new GetSettingsQueryHandler(context); + + var result = await handler.Handle(new GetSettingsQuery(), CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + result.Data.ShouldNotBeNull(); + result.Data.Count.ShouldBe(3); + } +} diff --git a/tests/Heimdall.Application.Tests/Handlers/Settings/RemoveAgentSettingHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Settings/RemoveAgentSettingHandlerTests.cs new file mode 100644 index 0000000..4a7f6f6 --- /dev/null +++ b/tests/Heimdall.Application.Tests/Handlers/Settings/RemoveAgentSettingHandlerTests.cs @@ -0,0 +1,40 @@ +using Heimdall.Application.Common; +using Heimdall.Application.Settings.Commands.RemoveAgentSetting; +using Heimdall.Application.Tests.Common; +using Heimdall.Domain.Entities; +using NSubstitute; + +namespace Heimdall.Application.Tests.Handlers.Settings; + +public class RemoveAgentSettingHandlerTests +{ + [Fact] + public async Task Remove_agent_setting_should_return_success() + { + var agentId = Guid.NewGuid(); + var setting = new AgentSetting(agentId, "agent.key", "value"); + var context = Substitute.For(); + context.AgentSettings.Returns(MockDbSetHelper.CreateFor([setting])); + context.SaveChangesWithRetryAsync(Arg.Any(), Arg.Any()).Returns(Task.CompletedTask); + var handler = new RemoveAgentSettingCommandHandler(context); + + var result = await handler.Handle( + new RemoveAgentSettingCommand(agentId, "agent.key"), CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + } + + [Fact] + public async Task Remove_nonexistent_agent_setting_should_return_not_found() + { + var context = Substitute.For(); + context.AgentSettings.Returns(MockDbSetHelper.CreateFor()); + var handler = new RemoveAgentSettingCommandHandler(context); + + var result = await handler.Handle( + new RemoveAgentSettingCommand(Guid.NewGuid(), "missing.key"), CancellationToken.None); + + result.IsSuccess.ShouldBeFalse(); + result.StatusCode.ShouldBe(404); + } +} diff --git a/tests/Heimdall.Application.Tests/Handlers/Settings/SetAgentSettingHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Settings/SetAgentSettingHandlerTests.cs new file mode 100644 index 0000000..bde3d1b --- /dev/null +++ b/tests/Heimdall.Application.Tests/Handlers/Settings/SetAgentSettingHandlerTests.cs @@ -0,0 +1,45 @@ +using Heimdall.Application.Common; +using Heimdall.Application.Settings.Commands.SetAgentSetting; +using Heimdall.Application.Tests.Common; +using Heimdall.Domain.Entities; +using NSubstitute; + +namespace Heimdall.Application.Tests.Handlers.Settings; + +public class SetAgentSettingHandlerTests +{ + [Fact] + public async Task Set_new_agent_setting_should_create() + { + var agentId = Guid.NewGuid(); + var context = Substitute.For(); + context.AgentSettings.Returns(MockDbSetHelper.CreateFor()); + context.SaveChangesWithRetryAsync(Arg.Any(), Arg.Any()).Returns(Task.CompletedTask); + var handler = new SetAgentSettingCommandHandler(context); + + var result = await handler.Handle( + new SetAgentSettingCommand(agentId, "agent.key", "agent-value"), CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + result.Data!.AgentId.ShouldBe(agentId); + result.Data.Key.ShouldBe("agent.key"); + result.Data.Value.ShouldBe("agent-value"); + } + + [Fact] + public async Task Set_existing_agent_setting_should_update() + { + var agentId = Guid.NewGuid(); + var existing = new AgentSetting(agentId, "agent.key", "old-value"); + var context = Substitute.For(); + context.AgentSettings.Returns(MockDbSetHelper.CreateFor([existing])); + context.SaveChangesWithRetryAsync(Arg.Any(), Arg.Any()).Returns(Task.CompletedTask); + var handler = new SetAgentSettingCommandHandler(context); + + var result = await handler.Handle( + new SetAgentSettingCommand(agentId, "agent.key", "new-value"), CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + result.Data!.Value.ShouldBe("new-value"); + } +} diff --git a/tests/Heimdall.Application.Tests/Handlers/Settings/UpdateAppSettingHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Settings/UpdateAppSettingHandlerTests.cs new file mode 100644 index 0000000..0258c75 --- /dev/null +++ b/tests/Heimdall.Application.Tests/Handlers/Settings/UpdateAppSettingHandlerTests.cs @@ -0,0 +1,41 @@ +using Heimdall.Application.Common; +using Heimdall.Application.Settings.Commands.UpdateAppSetting; +using Heimdall.Application.Tests.Common; +using Heimdall.Domain.Entities; +using NSubstitute; + +namespace Heimdall.Application.Tests.Handlers.Settings; + +public class UpdateAppSettingHandlerTests +{ + [Fact] + public async Task Update_setting_should_return_success() + { + var setting = new AppSetting("test.key", "old-value", "General"); + var context = Substitute.For(); + context.AppSettings.Returns(MockDbSetHelper.CreateFor([setting])); + context.SaveChangesWithRetryAsync(Arg.Any(), Arg.Any()).Returns(Task.CompletedTask); + var handler = new UpdateAppSettingCommandHandler(context); + + var result = await handler.Handle( + new UpdateAppSettingCommand("test.key", "new-value", Description: "Updated description"), + CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + result.Data!.Value.ShouldBe("new-value"); + } + + [Fact] + public async Task Update_nonexistent_setting_should_return_not_found() + { + var context = Substitute.For(); + context.AppSettings.Returns(MockDbSetHelper.CreateFor()); + var handler = new UpdateAppSettingCommandHandler(context); + + var result = await handler.Handle( + new UpdateAppSettingCommand("missing.key", "value"), CancellationToken.None); + + result.IsSuccess.ShouldBeFalse(); + result.StatusCode.ShouldBe(404); + } +} diff --git a/tests/Heimdall.Application.Tests/Handlers/Sites/DeleteSiteHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Sites/DeleteSiteHandlerTests.cs new file mode 100644 index 0000000..b9e0315 --- /dev/null +++ b/tests/Heimdall.Application.Tests/Handlers/Sites/DeleteSiteHandlerTests.cs @@ -0,0 +1,54 @@ +using Heimdall.Application.Common; +using Heimdall.Application.Sites.Commands.DeleteSite; +using Heimdall.Application.Tests.Common; +using Heimdall.Domain.Entities; +using NSubstitute; + +namespace Heimdall.Application.Tests.Handlers.Sites; + +public class DeleteSiteHandlerTests +{ + private readonly Site _existingSite = new("Test Site", "Paris", "Europe/Paris"); + + [Fact] + public async Task Delete_site_should_return_success() + { + var context = Substitute.For(); + context.Sites.Returns(MockDbSetHelper.CreateFor([_existingSite])); + var handler = new DeleteSiteHandler(context); + var command = new DeleteSiteCommand(_existingSite.Id); + + var result = await handler.Handle(command, CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + } + + [Fact] + public async Task Delete_nonexistent_site_should_return_not_found() + { + var context = Substitute.For(); + context.Sites.Returns(MockDbSetHelper.CreateFor([_existingSite])); + var handler = new DeleteSiteHandler(context); + var command = new DeleteSiteCommand(Guid.NewGuid()); + + var result = await handler.Handle(command, CancellationToken.None); + + result.IsSuccess.ShouldBeFalse(); + result.StatusCode.ShouldBe(404); + } + + [Fact] + public async Task Delete_site_should_soft_delete_and_save() + { + var context = Substitute.For(); + context.Sites.Returns(MockDbSetHelper.CreateFor([_existingSite])); + var handler = new DeleteSiteHandler(context); + var command = new DeleteSiteCommand(_existingSite.Id); + + await handler.Handle(command, CancellationToken.None); + + _existingSite.IsDeleted.ShouldBeTrue(); + _existingSite.DeletedAt.ShouldNotBeNull(); + await context.Received(1).SaveChangesWithRetryAsync(Arg.Any(), Arg.Any()); + } +} diff --git a/tests/Heimdall.Application.Tests/Handlers/Sites/GetSiteHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Sites/GetSiteHandlerTests.cs new file mode 100644 index 0000000..86ceb7a --- /dev/null +++ b/tests/Heimdall.Application.Tests/Handlers/Sites/GetSiteHandlerTests.cs @@ -0,0 +1,43 @@ +using Heimdall.Application.Common; +using Heimdall.Application.DTOs; +using Heimdall.Application.Sites.Queries.GetSite; +using Heimdall.Application.Tests.Common; +using Heimdall.Domain.Entities; +using NSubstitute; + +namespace Heimdall.Application.Tests.Handlers.Sites; + +public class GetSiteHandlerTests +{ + private readonly Site _existingSite = new("Test Site", "Paris", "Europe/Paris"); + + [Fact] + public async Task Get_site_should_return_site() + { + var context = Substitute.For(); + context.Sites.Returns(MockDbSetHelper.CreateFor([_existingSite])); + var handler = new GetSiteHandler(context); + var query = new GetSiteQuery(_existingSite.Id); + + var result = await handler.Handle(query, CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + result.Data.ShouldNotBeNull(); + result.Data.Name.ShouldBe("Test Site"); + result.Data.Timezone.ShouldBe("Europe/Paris"); + } + + [Fact] + public async Task Get_nonexistent_site_should_return_not_found() + { + var context = Substitute.For(); + context.Sites.Returns(MockDbSetHelper.CreateFor([_existingSite])); + var handler = new GetSiteHandler(context); + var query = new GetSiteQuery(Guid.NewGuid()); + + var result = await handler.Handle(query, CancellationToken.None); + + result.IsSuccess.ShouldBeFalse(); + result.StatusCode.ShouldBe(404); + } +} diff --git a/tests/Heimdall.Application.Tests/Handlers/Sites/GetSitesHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Sites/GetSitesHandlerTests.cs new file mode 100644 index 0000000..c8160f0 --- /dev/null +++ b/tests/Heimdall.Application.Tests/Handlers/Sites/GetSitesHandlerTests.cs @@ -0,0 +1,79 @@ +using Heimdall.Application.Common; +using Heimdall.Application.DTOs; +using Heimdall.Application.Sites.Queries.GetSites; +using Heimdall.Application.Tests.Common; +using Heimdall.Domain.Entities; +using NSubstitute; + +namespace Heimdall.Application.Tests.Handlers.Sites; + +public class GetSitesHandlerTests +{ + private readonly List _sites = + [ + new Site("Beta", "Paris", "Europe/Paris"), + new Site("Alpha", "Lyon", "Europe/Paris"), + new Site("Gamma", "Marseille", "Europe/Paris"), + ]; + + [Fact] + public async Task Get_sites_should_return_paginated_results() + { + var context = Substitute.For(); + context.Sites.Returns(MockDbSetHelper.CreateFor(_sites)); + var handler = new GetSitesHandler(context); + var query = new GetSitesQuery(Page: 1, PageSize: 10); + + var result = await handler.Handle(query, CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + result.Data.ShouldNotBeNull(); + result.Data.Items.Count.ShouldBe(3); + result.Data.TotalCount.ShouldBe(3); + } + + [Fact] + public async Task Get_sites_should_order_by_name() + { + var context = Substitute.For(); + context.Sites.Returns(MockDbSetHelper.CreateFor(_sites)); + var handler = new GetSitesHandler(context); + var query = new GetSitesQuery(Page: 1, PageSize: 10); + + var result = await handler.Handle(query, CancellationToken.None); + + result.Data!.Items[0].Name.ShouldBe("Alpha"); + result.Data.Items[1].Name.ShouldBe("Beta"); + result.Data.Items[2].Name.ShouldBe("Gamma"); + } + + [Fact] + public async Task Get_sites_should_respect_pagination() + { + var context = Substitute.For(); + context.Sites.Returns(MockDbSetHelper.CreateFor(_sites)); + var handler = new GetSitesHandler(context); + var query = new GetSitesQuery(Page: 1, PageSize: 2); + + var result = await handler.Handle(query, CancellationToken.None); + + result.Data!.Items.Count.ShouldBe(2); + result.Data.TotalCount.ShouldBe(3); + result.Data.Page.ShouldBe(1); + } + + [Fact] + public async Task Get_sites_empty_result_should_return_empty_list() + { + var context = Substitute.For(); + context.Sites.Returns(MockDbSetHelper.CreateFor()); + var handler = new GetSitesHandler(context); + var query = new GetSitesQuery(Page: 1, PageSize: 10); + + var result = await handler.Handle(query, CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + result.Data!.Items.ShouldBeEmpty(); + result.Data.TotalCount.ShouldBe(0); + } +} diff --git a/tests/Heimdall.Application.Tests/Handlers/Sites/UpdateSiteHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Sites/UpdateSiteHandlerTests.cs new file mode 100644 index 0000000..f617c1e --- /dev/null +++ b/tests/Heimdall.Application.Tests/Handlers/Sites/UpdateSiteHandlerTests.cs @@ -0,0 +1,57 @@ +using Heimdall.Application.Common; +using Heimdall.Application.DTOs; +using Heimdall.Application.Sites.Commands.UpdateSite; +using Heimdall.Application.Tests.Common; +using Heimdall.Domain.Entities; +using NSubstitute; + +namespace Heimdall.Application.Tests.Handlers.Sites; + +public class UpdateSiteHandlerTests +{ + private readonly Site _existingSite = new("Original Name", "Original Address", "Europe/Paris"); + + [Fact] + public async Task Update_site_should_return_success() + { + var context = Substitute.For(); + context.Sites.Returns(MockDbSetHelper.CreateFor([_existingSite])); + var handler = new UpdateSiteHandler(context); + var command = new UpdateSiteCommand(_existingSite.Id, "Updated Name", "New Address", "America/New_York"); + + var result = await handler.Handle(command, CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + result.Data.ShouldNotBeNull(); + result.Data.Name.ShouldBe("Updated Name"); + result.Data.Address.ShouldBe("New Address"); + result.Data.Timezone.ShouldBe("America/New_York"); + } + + [Fact] + public async Task Update_nonexistent_site_should_return_not_found() + { + var context = Substitute.For(); + context.Sites.Returns(MockDbSetHelper.CreateFor([_existingSite])); + var handler = new UpdateSiteHandler(context); + var command = new UpdateSiteCommand(Guid.NewGuid(), "Name", null, null); + + var result = await handler.Handle(command, CancellationToken.None); + + result.IsSuccess.ShouldBeFalse(); + result.StatusCode.ShouldBe(404); + } + + [Fact] + public async Task Update_site_should_call_save_changes() + { + var context = Substitute.For(); + context.Sites.Returns(MockDbSetHelper.CreateFor([_existingSite])); + var handler = new UpdateSiteHandler(context); + var command = new UpdateSiteCommand(_existingSite.Id, "Updated", null, null); + + await handler.Handle(command, CancellationToken.None); + + await context.Received(1).SaveChangesWithRetryAsync(Arg.Any(), Arg.Any()); + } +}