From 06247d4f5cd6ac7d0c655428e85740056a148065 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Thu, 23 Jul 2026 15:27:34 +0000 Subject: [PATCH] test(web): add Web.Tests unit tests and extended IntegrationTests --- .../Services/HeimdallAuthStateProvider.cs | 4 +- .../Controllers/AuditLogsControllerTests.cs | 38 +++ .../Controllers/GroupsControllerTests.cs | 115 +++++++ .../Controllers/HealthControllerTests.cs | 30 ++ .../Controllers/PermissionsControllerTests.cs | 43 +++ .../Controllers/PersonsControllerTests.cs | 129 ++++++++ .../Controllers/RolesControllerTests.cs | 62 ++++ .../Controllers/StatsControllerTests.cs | 42 +++ .../ControllerBaseExtensionsTests.cs | 66 ++++ .../Filters/ExceptionFilterTests.cs | 95 ++++++ .../Heimdall.Web.Tests/Hubs/EventsHubTests.cs | 101 +++++++ .../Services/HeimdallApiClientTests.cs | 283 ++++++++++++++++++ .../Services/TokenRefreshHandlerTests.cs | 99 ++++++ 13 files changed, 1105 insertions(+), 2 deletions(-) create mode 100644 tests/Heimdall.IntegrationTests/Controllers/AuditLogsControllerTests.cs create mode 100644 tests/Heimdall.IntegrationTests/Controllers/GroupsControllerTests.cs create mode 100644 tests/Heimdall.IntegrationTests/Controllers/HealthControllerTests.cs create mode 100644 tests/Heimdall.IntegrationTests/Controllers/PermissionsControllerTests.cs create mode 100644 tests/Heimdall.IntegrationTests/Controllers/PersonsControllerTests.cs create mode 100644 tests/Heimdall.IntegrationTests/Controllers/RolesControllerTests.cs create mode 100644 tests/Heimdall.IntegrationTests/Controllers/StatsControllerTests.cs create mode 100644 tests/Heimdall.Web.Tests/Controllers/ControllerBaseExtensionsTests.cs create mode 100644 tests/Heimdall.Web.Tests/Filters/ExceptionFilterTests.cs create mode 100644 tests/Heimdall.Web.Tests/Hubs/EventsHubTests.cs create mode 100644 tests/Heimdall.Web.Tests/Services/HeimdallApiClientTests.cs create mode 100644 tests/Heimdall.Web.Tests/Services/TokenRefreshHandlerTests.cs diff --git a/src/Heimdall.Web/Services/HeimdallAuthStateProvider.cs b/src/Heimdall.Web/Services/HeimdallAuthStateProvider.cs index aad46dc..81d9d4c 100644 --- a/src/Heimdall.Web/Services/HeimdallAuthStateProvider.cs +++ b/src/Heimdall.Web/Services/HeimdallAuthStateProvider.cs @@ -37,14 +37,14 @@ public class HeimdallAuthStateProvider : AuthenticationStateProvider } } - public async Task NotifyLoginAsync(AuthResponse response) + public virtual async Task NotifyLoginAsync(AuthResponse response) { await _storage.SetAsync(StorageKey, response); _authState.Login(response); NotifyAuthenticationStateChanged(Task.FromResult(CreateAuthenticationState(response))); } - public async Task NotifyLogoutAsync() + public virtual async Task NotifyLogoutAsync() { await _storage.DeleteAsync(StorageKey); _authState.Logout(); diff --git a/tests/Heimdall.IntegrationTests/Controllers/AuditLogsControllerTests.cs b/tests/Heimdall.IntegrationTests/Controllers/AuditLogsControllerTests.cs new file mode 100644 index 0000000..b0f1112 --- /dev/null +++ b/tests/Heimdall.IntegrationTests/Controllers/AuditLogsControllerTests.cs @@ -0,0 +1,38 @@ +using System.Net.Http.Json; +using System.Text.Json; +using Heimdall.IntegrationTests.Factories; +using Shouldly; + +namespace Heimdall.IntegrationTests.Controllers; + +public class AuditLogsControllerTests : PostgresTestBase +{ + public AuditLogsControllerTests(PostgreSqlContainerFixture postgres) : base(postgres) { } + + [Fact] + public async Task List_WithoutAuth_ReturnsUnauthorized() + { + var client = Factory.CreateClient(); + var response = await client.GetAsync("api/audit-logs?page=1&pageSize=20"); + response.StatusCode.ShouldBe(System.Net.HttpStatusCode.Unauthorized); + } + + [Fact] + public async Task List_WithAdminAuth_ReturnsOk() + { + var client = await Factory.CreateAdminClientAsync(); + var response = await client.GetAsync("api/audit-logs?page=1&pageSize=20"); + response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); + + var content = await response.Content.ReadFromJsonAsync(); + content.GetProperty("items").GetArrayLength().ShouldBeGreaterThanOrEqualTo(0); + } + + [Fact] + public async Task List_WithFilters_ReturnsOk() + { + var client = await Factory.CreateAdminClientAsync(); + var response = await client.GetAsync("api/audit-logs?resourceType=Site&action=Create&page=1&pageSize=20"); + response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); + } +} diff --git a/tests/Heimdall.IntegrationTests/Controllers/GroupsControllerTests.cs b/tests/Heimdall.IntegrationTests/Controllers/GroupsControllerTests.cs new file mode 100644 index 0000000..b3c29ab --- /dev/null +++ b/tests/Heimdall.IntegrationTests/Controllers/GroupsControllerTests.cs @@ -0,0 +1,115 @@ +using System.Net.Http.Json; +using System.Text.Json; +using Heimdall.IntegrationTests.Factories; +using Shouldly; + +namespace Heimdall.IntegrationTests.Controllers; + +public class GroupsControllerTests : PostgresTestBase +{ + public GroupsControllerTests(PostgreSqlContainerFixture postgres) : base(postgres) { } + + [Fact] + public async Task List_WithoutAuth_ReturnsUnauthorized() + { + var client = Factory.CreateClient(); + var response = await client.GetAsync("api/groups?page=1&pageSize=20"); + response.StatusCode.ShouldBe(System.Net.HttpStatusCode.Unauthorized); + } + + [Fact] + public async Task Create_WithoutAuth_ReturnsUnauthorized() + { + var client = Factory.CreateClient(); + var response = await client.PostAsJsonAsync("api/groups", new { name = "Test Group" }); + response.StatusCode.ShouldBe(System.Net.HttpStatusCode.Unauthorized); + } + + [Fact] + public async Task Create_WithAdminAuth_ReturnsOk() + { + var client = await Factory.CreateAdminClientAsync(); + var response = await client.PostAsJsonAsync("api/groups", new + { + name = $"Test Group {Guid.NewGuid():N}", + description = "Integration test group" + }); + response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); + } + + [Fact] + public async Task Create_GetById_ReturnsGroup() + { + var client = await Factory.CreateAdminClientAsync(); + var createResponse = await client.PostAsJsonAsync("api/groups", new + { + name = $"GetById Group {Guid.NewGuid():N}" + }); + var createContent = await createResponse.Content.ReadFromJsonAsync(); + var groupId = createContent.GetProperty("id").GetGuid(); + + var getResponse = await client.GetAsync($"api/groups/{groupId}"); + getResponse.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); + + var getContent = await getResponse.Content.ReadFromJsonAsync(); + getContent.GetProperty("id").GetGuid().ShouldBe(groupId); + } + + [Fact] + public async Task Update_WithAdminAuth_ReturnsOk() + { + var client = await Factory.CreateAdminClientAsync(); + var createResponse = await client.PostAsJsonAsync("api/groups", new + { + name = $"Update Group {Guid.NewGuid():N}" + }); + var createContent = await createResponse.Content.ReadFromJsonAsync(); + var groupId = createContent.GetProperty("id").GetGuid(); + + var updateResponse = await client.PutAsJsonAsync($"api/groups/{groupId}", new + { + name = $"Updated Group {Guid.NewGuid():N}", + description = "Updated description" + }); + updateResponse.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); + } + + [Fact] + public async Task Delete_WithAdminAuth_ReturnsOk() + { + var client = await Factory.CreateAdminClientAsync(); + var createResponse = await client.PostAsJsonAsync("api/groups", new + { + name = $"Delete Group {Guid.NewGuid():N}" + }); + var createContent = await createResponse.Content.ReadFromJsonAsync(); + var groupId = createContent.GetProperty("id").GetGuid(); + + var deleteResponse = await client.DeleteAsync($"api/groups/{groupId}"); + deleteResponse.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); + } + + [Fact] + public async Task List_WithAdminAuth_ReturnsOk() + { + var client = await Factory.CreateAdminClientAsync(); + var response = await client.GetAsync("api/groups?page=1&pageSize=20"); + response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); + } + + [Fact] + public async Task GetMembers_WithoutAuth_ReturnsUnauthorized() + { + var client = Factory.CreateClient(); + var response = await client.GetAsync($"api/groups/{Guid.NewGuid()}/users"); + response.StatusCode.ShouldBe(System.Net.HttpStatusCode.Unauthorized); + } + + [Fact] + public async Task GetById_NonExistent_ReturnsNotFound() + { + var client = await Factory.CreateAdminClientAsync(); + var response = await client.GetAsync($"api/groups/{Guid.NewGuid()}"); + response.StatusCode.ShouldBe(System.Net.HttpStatusCode.NotFound); + } +} diff --git a/tests/Heimdall.IntegrationTests/Controllers/HealthControllerTests.cs b/tests/Heimdall.IntegrationTests/Controllers/HealthControllerTests.cs new file mode 100644 index 0000000..bbaeacf --- /dev/null +++ b/tests/Heimdall.IntegrationTests/Controllers/HealthControllerTests.cs @@ -0,0 +1,30 @@ +using System.Net.Http.Json; +using System.Text.Json; +using Shouldly; + +namespace Heimdall.IntegrationTests.Controllers; + +public class HealthControllerTests : PostgresTestBase +{ + public HealthControllerTests(PostgreSqlContainerFixture postgres) : base(postgres) { } + + [Fact] + public async Task Health_ReturnsOk() + { + var client = Factory.CreateClient(); + var response = await client.GetAsync("/healthz"); + response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); + + var content = await response.Content.ReadFromJsonAsync(); + content.GetProperty("status").GetString().ShouldBe("healthy"); + } + + [Fact] + public async Task Health_ReturnsTimestamp() + { + var client = Factory.CreateClient(); + var response = await client.GetAsync("/healthz"); + var content = await response.Content.ReadFromJsonAsync(); + content.TryGetProperty("timestamp", out _).ShouldBeTrue(); + } +} diff --git a/tests/Heimdall.IntegrationTests/Controllers/PermissionsControllerTests.cs b/tests/Heimdall.IntegrationTests/Controllers/PermissionsControllerTests.cs new file mode 100644 index 0000000..88cdb0f --- /dev/null +++ b/tests/Heimdall.IntegrationTests/Controllers/PermissionsControllerTests.cs @@ -0,0 +1,43 @@ +using System.Net.Http.Json; +using System.Text.Json; +using Heimdall.IntegrationTests.Factories; +using Shouldly; + +namespace Heimdall.IntegrationTests.Controllers; + +public class PermissionsControllerTests : PostgresTestBase +{ + public PermissionsControllerTests(PostgreSqlContainerFixture postgres) : base(postgres) { } + + [Fact] + public async Task List_WithoutAuth_ReturnsUnauthorized() + { + var client = Factory.CreateClient(); + var response = await client.GetAsync("api/permissions"); + response.StatusCode.ShouldBe(System.Net.HttpStatusCode.Unauthorized); + } + + [Fact] + public async Task List_WithAdminAuth_ReturnsOk() + { + var client = await Factory.CreateAdminClientAsync(); + var response = await client.GetAsync("api/permissions"); + response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); + + var content = await response.Content.ReadFromJsonAsync(); + content.GetProperty("permissions").GetArrayLength().ShouldBeGreaterThan(0); + } + + [Fact] + public async Task List_ContainsExpectedPermissions() + { + var client = await Factory.CreateAdminClientAsync(); + var response = await client.GetAsync("api/permissions"); + var content = await response.Content.ReadFromJsonAsync(); + var permissions = content.GetProperty("permissions").EnumerateArray().ToList(); + + permissions.Any(p => p.GetProperty("name").GetString() == "Site.Read").ShouldBeTrue(); + permissions.Any(p => p.GetProperty("name").GetString() == "Camera.Read").ShouldBeTrue(); + permissions.Any(p => p.GetProperty("name").GetString() == "Event.Read").ShouldBeTrue(); + } +} diff --git a/tests/Heimdall.IntegrationTests/Controllers/PersonsControllerTests.cs b/tests/Heimdall.IntegrationTests/Controllers/PersonsControllerTests.cs new file mode 100644 index 0000000..9020bbe --- /dev/null +++ b/tests/Heimdall.IntegrationTests/Controllers/PersonsControllerTests.cs @@ -0,0 +1,129 @@ +using System.Net.Http.Json; +using System.Text.Json; +using Heimdall.IntegrationTests.Factories; +using Shouldly; + +namespace Heimdall.IntegrationTests.Controllers; + +public class PersonsControllerTests : PostgresTestBase +{ + public PersonsControllerTests(PostgreSqlContainerFixture postgres) : base(postgres) { } + + [Fact] + public async Task GetAll_WithoutAuth_ReturnsUnauthorized() + { + var client = Factory.CreateClient(); + var response = await client.GetAsync("api/persons"); + response.StatusCode.ShouldBe(System.Net.HttpStatusCode.Unauthorized); + } + + [Fact] + public async Task GetAll_WithAdminAuth_ReturnsOk() + { + var client = await Factory.CreateAdminClientAsync(); + var response = await client.GetAsync("api/persons"); + response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); + + var content = await response.Content.ReadFromJsonAsync(); + content.ValueKind.ShouldBe(System.Text.Json.JsonValueKind.Array); + } + + [Fact] + public async Task Create_WithoutAuth_ReturnsUnauthorized() + { + var client = Factory.CreateClient(); + var response = await client.PostAsJsonAsync("api/persons", new + { + displayName = "Test Person", + category = "employee" + }); + response.StatusCode.ShouldBe(System.Net.HttpStatusCode.Unauthorized); + } + + [Fact] + public async Task Create_WithAdminAuth_ReturnsOk() + { + var client = await Factory.CreateAdminClientAsync(); + var response = await client.PostAsJsonAsync("api/persons", new + { + displayName = $"Person {Guid.NewGuid():N}", + category = "employee" + }); + response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); + } + + [Fact] + public async Task Create_GetById_ReturnsPerson() + { + var client = await Factory.CreateAdminClientAsync(); + var createResponse = await client.PostAsJsonAsync("api/persons", new + { + displayName = $"Get Person {Guid.NewGuid():N}", + category = "visitor" + }); + var createContent = await createResponse.Content.ReadFromJsonAsync(); + var personId = createContent.GetProperty("id").GetGuid(); + + var getResponse = await client.GetAsync($"api/persons/{personId}"); + getResponse.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); + + var getContent = await getResponse.Content.ReadFromJsonAsync(); + getContent.GetProperty("id").GetGuid().ShouldBe(personId); + } + + [Fact] + public async Task GetById_NonExistent_ReturnsNotFound() + { + var client = await Factory.CreateAdminClientAsync(); + var response = await client.GetAsync($"api/persons/{Guid.NewGuid()}"); + response.StatusCode.ShouldBe(System.Net.HttpStatusCode.NotFound); + } + + [Fact] + public async Task Update_WithAdminAuth_ReturnsOk() + { + var client = await Factory.CreateAdminClientAsync(); + var createResponse = await client.PostAsJsonAsync("api/persons", new + { + displayName = $"Update Person {Guid.NewGuid():N}", + category = "employee" + }); + var createContent = await createResponse.Content.ReadFromJsonAsync(); + var personId = createContent.GetProperty("id").GetGuid(); + + var updateResponse = await client.PutAsJsonAsync($"api/persons/{personId}", new + { + displayName = $"Updated Person {Guid.NewGuid():N}", + category = "employee", + isWatchlisted = false + }); + updateResponse.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); + } + + [Fact] + public async Task Delete_WithAdminAuth_ReturnsOk() + { + var client = await Factory.CreateAdminClientAsync(); + var createResponse = await client.PostAsJsonAsync("api/persons", new + { + displayName = $"Delete Person {Guid.NewGuid():N}", + category = "employee" + }); + var createContent = await createResponse.Content.ReadFromJsonAsync(); + var personId = createContent.GetProperty("id").GetGuid(); + + var deleteResponse = await client.DeleteAsync($"api/persons/{personId}"); + deleteResponse.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); + } + + [Fact] + public async Task GetAll_WithCategoryFilter_ReturnsOk() + { + var client = await Factory.CreateAdminClientAsync(); + var response = await client.GetAsync("api/persons?category=employee"); + response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); + + var content = await response.Content.ReadFromJsonAsync(); + content.ValueKind.ShouldBe(System.Text.Json.JsonValueKind.Array); + } +} diff --git a/tests/Heimdall.IntegrationTests/Controllers/RolesControllerTests.cs b/tests/Heimdall.IntegrationTests/Controllers/RolesControllerTests.cs new file mode 100644 index 0000000..4c32533 --- /dev/null +++ b/tests/Heimdall.IntegrationTests/Controllers/RolesControllerTests.cs @@ -0,0 +1,62 @@ +using System.Net.Http.Json; +using System.Text.Json; +using Heimdall.IntegrationTests.Factories; +using Shouldly; + +namespace Heimdall.IntegrationTests.Controllers; + +public class RolesControllerTests : PostgresTestBase +{ + public RolesControllerTests(PostgreSqlContainerFixture postgres) : base(postgres) { } + + [Fact] + public async Task List_WithoutAuth_ReturnsUnauthorized() + { + var client = Factory.CreateClient(); + var response = await client.GetAsync("api/roles"); + response.StatusCode.ShouldBe(System.Net.HttpStatusCode.Unauthorized); + } + + [Fact] + public async Task List_WithAdminAuth_ReturnsOk() + { + var client = await Factory.CreateAdminClientAsync(); + var response = await client.GetAsync("api/roles"); + response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); + + var content = await response.Content.ReadFromJsonAsync(); + content.GetProperty("roles").GetArrayLength().ShouldBeGreaterThan(0); + } + + [Fact] + public async Task GetByName_WithAdminAuth_ReturnsRole() + { + var client = await Factory.CreateAdminClientAsync(); + var response = await client.GetAsync("api/roles/Admin"); + response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); + + var content = await response.Content.ReadFromJsonAsync(); + content.GetProperty("name").GetString().ShouldBe("Admin"); + content.GetProperty("permissions").GetArrayLength().ShouldBeGreaterThan(0); + } + + [Fact] + public async Task GetByName_NonExistent_ReturnsNotFound() + { + var client = await Factory.CreateAdminClientAsync(); + var response = await client.GetAsync("api/roles/NonExistentRole"); + response.StatusCode.ShouldBe(System.Net.HttpStatusCode.NotFound); + } + + [Fact] + public async Task List_ContainsExpectedRoles() + { + var client = await Factory.CreateAdminClientAsync(); + var response = await client.GetAsync("api/roles"); + var content = await response.Content.ReadFromJsonAsync(); + var roles = content.GetProperty("roles").EnumerateArray().ToList(); + + roles.Any(r => r.GetProperty("name").GetString() == "Admin").ShouldBeTrue(); + roles.Any(r => r.GetProperty("name").GetString() == "Viewer").ShouldBeTrue(); + } +} diff --git a/tests/Heimdall.IntegrationTests/Controllers/StatsControllerTests.cs b/tests/Heimdall.IntegrationTests/Controllers/StatsControllerTests.cs new file mode 100644 index 0000000..43a094d --- /dev/null +++ b/tests/Heimdall.IntegrationTests/Controllers/StatsControllerTests.cs @@ -0,0 +1,42 @@ +using System.Net.Http.Json; +using Heimdall.IntegrationTests.Factories; +using Shouldly; + +namespace Heimdall.IntegrationTests.Controllers; + +public class StatsControllerTests : PostgresTestBase +{ + public StatsControllerTests(PostgreSqlContainerFixture postgres) : base(postgres) { } + + [Fact] + public async Task GetStats_WithoutAuth_ReturnsUnauthorized() + { + var client = Factory.CreateClient(); + var response = await client.GetAsync("api/stats"); + response.StatusCode.ShouldBe(System.Net.HttpStatusCode.Unauthorized); + } + + [Fact] + public async Task GetStats_WithAdminAuth_ReturnsOk() + { + var client = await Factory.CreateAdminClientAsync(); + var response = await client.GetAsync("api/stats"); + response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); + } + + [Fact] + public async Task GetAgentStats_WithoutAuth_ReturnsUnauthorized() + { + var client = Factory.CreateClient(); + var response = await client.GetAsync("api/stats/agent-stats"); + response.StatusCode.ShouldBe(System.Net.HttpStatusCode.Unauthorized); + } + + [Fact] + public async Task GetAgentStats_WithAdminAuth_ReturnsOk() + { + var client = await Factory.CreateAdminClientAsync(); + var response = await client.GetAsync("api/stats/agent-stats"); + response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); + } +} diff --git a/tests/Heimdall.Web.Tests/Controllers/ControllerBaseExtensionsTests.cs b/tests/Heimdall.Web.Tests/Controllers/ControllerBaseExtensionsTests.cs new file mode 100644 index 0000000..7274210 --- /dev/null +++ b/tests/Heimdall.Web.Tests/Controllers/ControllerBaseExtensionsTests.cs @@ -0,0 +1,66 @@ +using System.Security.Claims; +using Heimdall.Api.Controllers; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Routing; + +namespace Heimdall.Web.Tests.Controllers; + +public class ControllerBaseExtensionsTests +{ + private static TestController CreateControllerWithUser(string? nameIdentifier) + { + var claims = new List(); + if (nameIdentifier is not null) + claims.Add(new Claim(ClaimTypes.NameIdentifier, nameIdentifier)); + + var identity = new ClaimsIdentity(claims, "test"); + var principal = new ClaimsPrincipal(identity); + + var controller = new TestController + { + ControllerContext = new ControllerContext + { + HttpContext = new DefaultHttpContext + { + User = principal + } + } + }; + return controller; + } + + [Fact] + public void TryGetUserId_WithValidGuid_ReturnsTrueAndSetsUserId() + { + var expected = Guid.NewGuid(); + var ctrl = CreateControllerWithUser(expected.ToString()); + + var result = ctrl.TryGetUserId(out var userId); + + Assert.True(result); + Assert.Equal(expected, userId); + } + + [Fact] + public void TryGetUserId_WithInvalidClaimValue_ReturnsFalse() + { + var ctrl = CreateControllerWithUser("not-a-guid"); + + var result = ctrl.TryGetUserId(out _); + + Assert.False(result); + } + + [Fact] + public void TryGetUserId_WithMissingClaim_ReturnsFalse() + { + var ctrl = CreateControllerWithUser(null); + + var result = ctrl.TryGetUserId(out _); + + Assert.False(result); + } +} + +public class TestController : ControllerBase { } diff --git a/tests/Heimdall.Web.Tests/Filters/ExceptionFilterTests.cs b/tests/Heimdall.Web.Tests/Filters/ExceptionFilterTests.cs new file mode 100644 index 0000000..1584cd0 --- /dev/null +++ b/tests/Heimdall.Web.Tests/Filters/ExceptionFilterTests.cs @@ -0,0 +1,95 @@ +using Heimdall.Api.Filters; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Abstractions; +using Microsoft.AspNetCore.Mvc.Filters; +using Microsoft.AspNetCore.Routing; +using Microsoft.Extensions.Logging; +using NSubstitute; + +namespace Heimdall.Web.Tests.Filters; + +public class ExceptionFilterTests +{ + private static ExceptionContext CreateContext(Exception exception) + { + var logger = Substitute.For>(); + var httpContext = new DefaultHttpContext(); + var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor()); + + var context = new ExceptionContext(actionContext, []) + { + Exception = exception + }; + + var filter = new ExceptionFilter(logger); + filter.OnException(context); + return context; + } + + [Fact] + public void OnException_SetsStatusCode500() + { + var context = CreateContext(new InvalidOperationException("Test error")); + + var result = context.Result as ObjectResult; + Assert.NotNull(result); + Assert.Equal(500, result.StatusCode); + } + + [Fact] + public void OnException_SetsExceptionHandledToTrue() + { + var context = CreateContext(new InvalidOperationException("Test error")); + + Assert.True(context.ExceptionHandled); + } + + [Fact] + public void OnException_ReturnsExpectedErrorStructure() + { + var context = CreateContext(new InvalidOperationException("Test error")); + + var result = context.Result as ObjectResult; + Assert.NotNull(result); + + var value = result.Value; + Assert.NotNull(value); + + var valueType = value.GetType(); + var dict = valueType.GetProperties() + .ToDictionary(p => p.Name, p => p.GetValue(value)); + + Assert.True(dict.ContainsKey("error")); + + var error = dict["error"]; + var errorType = error!.GetType(); + var errorDict = errorType.GetProperties() + .ToDictionary(p => p.Name, p => p.GetValue(error)); + + Assert.Equal("InternalServerError", errorDict["code"]?.ToString()); + Assert.Equal("An unexpected error occurred", errorDict["message"]?.ToString()); + } + + [Fact] + public void OnException_LogsErrorMessage() + { + var logger = Substitute.For>(); + var httpContext = new DefaultHttpContext(); + var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor()); + var context = new ExceptionContext(actionContext, []) + { + Exception = new InvalidOperationException("Test error") + }; + + var filter = new ExceptionFilter(logger); + filter.OnException(context); + + logger.Received(1).Log( + LogLevel.Error, + Arg.Any(), + Arg.Any(), + context.Exception, + Arg.Any>()); + } +} diff --git a/tests/Heimdall.Web.Tests/Hubs/EventsHubTests.cs b/tests/Heimdall.Web.Tests/Hubs/EventsHubTests.cs new file mode 100644 index 0000000..cfcfbb2 --- /dev/null +++ b/tests/Heimdall.Web.Tests/Hubs/EventsHubTests.cs @@ -0,0 +1,101 @@ +using Heimdall.Api.Hubs; +using Microsoft.AspNetCore.SignalR; +using Microsoft.Extensions.Logging; +using NSubstitute; + +namespace Heimdall.Web.Tests.Hubs; + +public sealed class EventsHubTests : IDisposable +{ + private readonly ISingleClientProxy _caller; + private readonly IGroupManager _groups; + private readonly ILogger _logger; + private readonly EventsHub _hub; + + public EventsHubTests() + { + _caller = Substitute.For(); + var clients = Substitute.For(); + clients.Caller.Returns(_caller); + _groups = Substitute.For(); + _logger = Substitute.For>(); + + _hub = new EventsHub(_logger) + { + Groups = _groups, + Clients = clients, + Context = Substitute.For() + }; + _hub.Context.ConnectionId.Returns("test-connection"); + } + + public void Dispose() + { + _hub.Dispose(); + } + + [Fact] + public async Task JoinSiteEvents_WithValidGuid_AddsToGroup() + { + var siteId = Guid.NewGuid().ToString(); + + await _hub.JoinSiteEvents(siteId); + + await _groups.Received(1).AddToGroupAsync("test-connection", $"site_{siteId}"); + } + + [Fact] + public async Task JoinSiteEvents_WithInvalidGuid_SendsError_DoesNotAddToGroup() + { + await _hub.JoinSiteEvents("not-a-guid"); + + await _groups.DidNotReceiveWithAnyArgs().AddToGroupAsync(default!, default!); + } + + [Fact] + public async Task JoinSiteEvents_WithEmptyString_DoesNotAddToGroup() + { + await _hub.JoinSiteEvents(""); + + await _groups.DidNotReceiveWithAnyArgs().AddToGroupAsync(default!, default!); + } + + [Fact] + public async Task LeaveSiteEvents_WithValidGuid_RemovesFromGroup() + { + var siteId = Guid.NewGuid().ToString(); + + await _hub.LeaveSiteEvents(siteId); + + await _groups.Received(1).RemoveFromGroupAsync("test-connection", $"site_{siteId}"); + } + + [Fact] + public async Task LeaveSiteEvents_WithInvalidGuid_DoesNothing() + { + await _hub.LeaveSiteEvents("bad-id"); + + await _groups.DidNotReceiveWithAnyArgs().RemoveFromGroupAsync(default!, default!); + } + + [Fact] + public async Task OnConnectedAsync_DoesNotThrow() + { + var exception = await Record.ExceptionAsync(() => _hub.OnConnectedAsync()); + Assert.Null(exception); + } + + [Fact] + public async Task OnDisconnectedAsync_WithException_DoesNotThrow() + { + var exception = await Record.ExceptionAsync(() => _hub.OnDisconnectedAsync(new InvalidOperationException("test"))); + Assert.Null(exception); + } + + [Fact] + public async Task OnDisconnectedAsync_WithoutException_DoesNotThrow() + { + var exception = await Record.ExceptionAsync(() => _hub.OnDisconnectedAsync(null)); + Assert.Null(exception); + } +} diff --git a/tests/Heimdall.Web.Tests/Services/HeimdallApiClientTests.cs b/tests/Heimdall.Web.Tests/Services/HeimdallApiClientTests.cs new file mode 100644 index 0000000..7a97aee --- /dev/null +++ b/tests/Heimdall.Web.Tests/Services/HeimdallApiClientTests.cs @@ -0,0 +1,283 @@ +using System.Net; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; +using Heimdall.Web.Services; +using NSubstitute; + +namespace Heimdall.Web.Tests.Services; + +public sealed class HeimdallApiClientTests : IDisposable +{ + private readonly MockHttpMessageHandler _handler; + private readonly HttpClient _httpClient; + private readonly IHttpClientFactory _httpFactory; + private readonly AuthState _authState; + private readonly HeimdallApiClient _sut; + + public HeimdallApiClientTests() + { + _handler = new MockHttpMessageHandler(); + _httpClient = new HttpClient(_handler) { BaseAddress = new Uri("http://localhost:8080/") }; + _httpFactory = Substitute.For(); + _httpFactory.CreateClient("HeimdallApi").Returns(_httpClient); + _authState = new AuthState(); + _sut = new HeimdallApiClient(_httpFactory, _authState); + } + + public void Dispose() => _httpClient.Dispose(); + + private void SetAuthToken(string token = "test-token") + { + _authState.Login(new AuthResponse( + token, "refresh-token", DateTime.UtcNow.AddHours(1), false, + new UserInfo(Guid.NewGuid(), "test@test.com", "Test", ["Admin"]))); + } + + // ── Profile ────────────────────────────────────────────────────── + + [Fact] + public async Task GetMyProfileAsync_WhenSuccess_ReturnsUserItem() + { + SetAuthToken(); + var expected = new UserItem { Id = Guid.NewGuid(), Email = "test@test.com", DisplayName = "Test" }; + _handler.QueueResponse(HttpStatusCode.OK, expected); + + var result = await _sut.GetMyProfileAsync(); + + Assert.NotNull(result); + Assert.Equal(expected.Id, result.Id); + Assert.Equal(expected.Email, result.Email); + } + + [Fact] + public async Task GetMyProfileAsync_WhenFails_ThrowsHttpRequestException() + { + SetAuthToken(); + _handler.QueueResponse(HttpStatusCode.Unauthorized); + + await Assert.ThrowsAsync(() => _sut.GetMyProfileAsync()); + } + + [Fact] + public async Task GetMyProfileAsync_SendsAuthHeader() + { + SetAuthToken("my-jwt-token"); + _handler.QueueResponse(HttpStatusCode.OK, new UserItem()); + + await _sut.GetMyProfileAsync(); + + var sent = _handler.LastRequest; + Assert.NotNull(sent); + Assert.Equal("Bearer my-jwt-token", sent.Headers.Authorization?.ToString()); + } + + // ── Auth ───────────────────────────────────────────────────────── + + [Fact] + public async Task LoginAsync_WhenSuccess_ReturnsAuthResponse() + { + var expected = new AuthResponse("access", "refresh", DateTime.UtcNow.AddHours(1), false, + new UserInfo(Guid.NewGuid(), "a@b.com", "A", null)); + _handler.QueueResponse(HttpStatusCode.OK, expected); + + var result = await _sut.LoginAsync("a@b.com", "pwd"); + + Assert.NotNull(result); + Assert.Equal("access", result.AccessToken); + } + + [Fact] + public async Task LoginAsync_WhenFails_ReturnsNull() + { + _handler.QueueResponse(HttpStatusCode.Unauthorized); + + var result = await _sut.LoginAsync("a@b.com", "wrong"); + + Assert.Null(result); + } + + // ── Groups ─────────────────────────────────────────────────────── + + [Fact] + public async Task GetGroupsAsync_ReturnsPagedData() + { + SetAuthToken(); + var expected = new PagedData([new GroupItem { Id = Guid.NewGuid(), Name = "G1" }], 1, 1, 20); + _handler.QueueResponse(HttpStatusCode.OK, expected); + + var result = await _sut.GetGroupsAsync(); + + Assert.NotNull(result); + Assert.Single(result.Items); + Assert.Equal("G1", result.Items[0].Name); + } + + [Fact] + public async Task CreateGroupAsync_WhenSuccess_ReturnsGroup() + { + SetAuthToken(); + var expected = new GroupItem { Id = Guid.NewGuid(), Name = "New Group" }; + _handler.QueueResponse(HttpStatusCode.OK, expected); + + var result = await _sut.CreateGroupAsync("New Group", "desc"); + + Assert.NotNull(result); + Assert.Equal("New Group", result.Name); + } + + [Fact] + public async Task CreateGroupAsync_WhenFails_ReturnsNull() + { + SetAuthToken(); + _handler.QueueResponse(HttpStatusCode.BadRequest); + + var result = await _sut.CreateGroupAsync("Bad", null); + + Assert.Null(result); + } + + [Fact] + public async Task DeleteGroupAsync_WhenSuccess_ReturnsTrue() + { + SetAuthToken(); + _handler.QueueResponse(HttpStatusCode.OK); + + var result = await _sut.DeleteGroupAsync(Guid.NewGuid()); + + Assert.True(result); + } + + [Fact] + public async Task DeleteGroupAsync_WhenFails_ReturnsFalse() + { + SetAuthToken(); + _handler.QueueResponse(HttpStatusCode.NotFound); + + var result = await _sut.DeleteGroupAsync(Guid.NewGuid()); + + Assert.False(result); + } + + [Fact] + public async Task AddUserToGroupAsync_WhenSuccess_ReturnsTrue() + { + SetAuthToken(); + _handler.QueueResponse(HttpStatusCode.OK); + + var result = await _sut.AddUserToGroupAsync(Guid.NewGuid(), Guid.NewGuid()); + + Assert.True(result); + } + + [Fact] + public async Task RemoveUserFromGroupAsync_WhenSuccess_ReturnsTrue() + { + SetAuthToken(); + _handler.QueueResponse(HttpStatusCode.OK); + + var result = await _sut.RemoveUserFromGroupAsync(Guid.NewGuid(), Guid.NewGuid()); + + Assert.True(result); + } + + // ── Roles & Permissions ────────────────────────────────────────── + + [Fact] + public async Task GetRolesAsync_ReturnsRoleList() + { + SetAuthToken(); + var expected = new RolesListResponse([new RoleItem("Admin", ["perm1"])]); + _handler.QueueResponse(HttpStatusCode.OK, expected); + + var result = await _sut.GetRolesAsync(); + + Assert.Single(result); + Assert.Equal("Admin", result[0].Name); + } + + [Fact] + public async Task GetPermissionsAsync_ReturnsPermissionList() + { + SetAuthToken(); + var expected = new PermissionsListResponse([new PermissionItem("Site.Read", "Read", "Sites")]); + _handler.QueueResponse(HttpStatusCode.OK, expected); + + var result = await _sut.GetPermissionsAsync(); + + Assert.Single(result); + Assert.Equal("Site.Read", result[0].Name); + } + + // ── Stats ──────────────────────────────────────────────────────── + + [Fact] + public async Task GetStatsAsync_ReturnsStats() + { + SetAuthToken(); + var expected = new StatsResult(1, 2, 3, 4, 5, 6, 7, 8, 9); + _handler.QueueResponse(HttpStatusCode.OK, expected); + + var result = await _sut.GetStatsAsync(); + + Assert.NotNull(result); + Assert.Equal(1, result.TotalSites); + Assert.Equal(2, result.TotalCameras); + } + + // ── Audit Logs ─────────────────────────────────────────────────── + + [Fact] + public async Task GetAuditLogsAsync_WithFilters_ReturnsPagedData() + { + SetAuthToken(); + var expected = new PagedData( + [new AuditLogItem { Id = Guid.NewGuid(), Action = "Create", ResourceType = "Site" }], 1, 1, 20); + _handler.QueueResponse(HttpStatusCode.OK, expected); + + var result = await _sut.GetAuditLogsAsync("Site", "Create"); + + Assert.NotNull(result); + Assert.Single(result.Items); + Assert.Equal("Create", result.Items[0].Action); + } + + // ── Auth header presence (no token) ────────────────────────────── + + [Fact] + public async Task GetMyProfileAsync_WithoutToken_DoesNotSendAuthHeader() + { + _handler.QueueResponse(HttpStatusCode.OK, new UserItem()); + + await _sut.GetMyProfileAsync(); + + var sent = _handler.LastRequest; + Assert.NotNull(sent); + Assert.Null(sent.Headers.Authorization); + } +} + +public class MockHttpMessageHandler : HttpMessageHandler +{ + private readonly Queue _responses = new(); + public HttpRequestMessage? LastRequest { get; private set; } + + public void QueueResponse(HttpStatusCode status, object? body = null) + { + var response = new HttpResponseMessage(status); + if (body is not null) + response.Content = JsonContent.Create(body, options: new JsonSerializerOptions + { + PropertyNameCaseInsensitive = true, + PropertyNamingPolicy = JsonNamingPolicy.CamelCase + }); + _responses.Enqueue(response); + } + + protected override Task SendAsync(HttpRequestMessage request, CancellationToken ct) + { + LastRequest = request; + var response = _responses.Count > 0 ? _responses.Dequeue() : new HttpResponseMessage(HttpStatusCode.OK); + return Task.FromResult(response); + } +} diff --git a/tests/Heimdall.Web.Tests/Services/TokenRefreshHandlerTests.cs b/tests/Heimdall.Web.Tests/Services/TokenRefreshHandlerTests.cs new file mode 100644 index 0000000..215d4b9 --- /dev/null +++ b/tests/Heimdall.Web.Tests/Services/TokenRefreshHandlerTests.cs @@ -0,0 +1,99 @@ +using System.Net; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; +using Heimdall.Web.Services; +using Microsoft.Extensions.Configuration; +using NSubstitute; + +namespace Heimdall.Web.Tests.Services; + +public sealed class TokenRefreshHandlerTests : IDisposable +{ + private readonly MockInnerHandler _innerHandler; + private readonly HttpClient _httpClient; + private readonly AuthState _authState; + private readonly TokenRefreshHandler _handler; + + public TokenRefreshHandlerTests() + { + _innerHandler = new MockInnerHandler(); + _authState = new AuthState(); + var authStateProvider = Substitute.For(null!, _authState); + + var config = Substitute.For(); + config.GetValue("ApiBaseUrl").Returns("http://localhost:8080"); + + _handler = new TokenRefreshHandler(_authState, authStateProvider, config); + + var pipeline = _innerHandler.CreatePipeline(_handler); + _httpClient = new HttpClient(pipeline) { BaseAddress = new Uri("http://localhost:8080/") }; + } + + public void Dispose() => _httpClient.Dispose(); + + [Fact] + public async Task SendAsync_Non401Response_PassesThrough() + { + _innerHandler.QueueResponse(HttpStatusCode.OK); + + var response = await _httpClient.GetAsync("api/sites"); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact] + public async Task SendAsync_401WithoutRefreshToken_DoesNotRetry() + { + _innerHandler.QueueResponse(HttpStatusCode.Unauthorized); + + var response = await _httpClient.GetAsync("api/sites"); + + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Equal(1, _innerHandler.CallCount); + } + + [Fact] + public async Task SendAsync_AuthEndpoint_DoesNotIntercept() + { + _innerHandler.QueueResponse(HttpStatusCode.Unauthorized); + + var response = await _httpClient.PostAsync("api/auth/login", null); + + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Equal(1, _innerHandler.CallCount); + } +} + +public class MockInnerHandler : HttpMessageHandler +{ + private readonly Queue _responses = new(); + public int CallCount { get; private set; } + public List Requests { get; } = []; + + public void QueueResponse(HttpStatusCode status, object? body = null) + { + var response = new HttpResponseMessage(status); + if (body is not null) + response.Content = JsonContent.Create(body, options: new JsonSerializerOptions + { + PropertyNameCaseInsensitive = true, + PropertyNamingPolicy = JsonNamingPolicy.CamelCase + }); + _responses.Enqueue(response); + } + + protected override Task SendAsync(HttpRequestMessage request, CancellationToken ct) + { + CallCount++; + Requests.Add(request); + var response = _responses.Count > 0 ? _responses.Dequeue() : new HttpResponseMessage(HttpStatusCode.OK); + return Task.FromResult(response); + } + + public HttpMessageHandler CreatePipeline(DelegatingHandler handler) + { + handler.InnerHandler = this; + return handler; + } +}