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); } }