using Govor.API.Hubs; using Govor.API.Hubs.Infrastructure; using Govor.Application.PrivateUserChats; using Govor.Application.Profiles; using Govor.Application.PushNotifications; using Govor.Contracts.Responses.SignalR; using Govor.Domain.Common; using Govor.Domain.Models; using Govor.Domain.Models.Messages; using Govor.Domain.Models.Users; using Microsoft.AspNetCore.SignalR; using Microsoft.Extensions.Logging.Abstractions; using Moq; using SmartRes; namespace Govor.Server.Tests; [TestFixture] public class NotificationTests { private TestDatabase _db = null!; private Mock _push = null!; private Mock _proxy = null!; private ChatNotificationService _notifier = null!; private readonly List<(string Method, string[] Groups)> _events = []; private string[] _targetGroups = []; private Guid _aliceSession; private Guid _bobSession; [SetUp] public void SetUp() { _db = new TestDatabase(); _events.Clear(); _aliceSession = AddSession(_db.Alice); _bobSession = AddSession(_db.Bob); AddSession(_db.Bob, revoked: true); AddSession(_db.Outsider); _proxy = new Mock(); _proxy.Setup(p => p.SendCoreAsync(It.IsAny(), It.IsAny(), It.IsAny())) .Callback((method, _, _) => _events.Add((method, _targetGroups))) .Returns(Task.CompletedTask); var clients = new Mock(); clients.Setup(c => c.Groups(It.IsAny>())) .Callback>(groups => _targetGroups = groups.ToArray()) .Returns(_proxy.Object); var hub = new Mock>(); hub.SetupGet(h => h.Clients).Returns(clients.Object); var chats = new Mock(); chats.Setup(c => c.GetPrivateChatAsync(_db.ChatId)) .ReturnsAsync(Result.Success(_db.Context.PrivateChats.Single())); var profiles = new Mock(); profiles.Setup(p => p.GetUserProfileAsync(_db.Alice)) .ReturnsAsync(Result.Success(new UserProfile { Id = _db.Alice, Username = "Alice" })); _push = new Mock(); _push.Setup(p => p.SendToUsersAsync(It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny?>())) .ReturnsAsync(Govor.Domain.Common.Result.Success()); _notifier = new ChatNotificationService(hub.Object, _push.Object, chats.Object, profiles.Object, _db.Context, NullLogger.Instance); } [TearDown] public void TearDown() => _db.Dispose(); [Test] public async Task PrivateMessageReachesBothActiveSessionsAndPushGoesOnlyToRecipient() { var message = Message(); await _notifier.NotifyMessageSentAsync(message); await _notifier.DeliverPushAsync(message); Assert.That(_events.Single(e => e.Method == ChatHubConstants.ReceiveMessage).Groups, Is.EquivalentTo(new[] { ChatHubConstants.GetSessionGroup(_aliceSession), ChatHubConstants.GetSessionGroup(_bobSession) })); Assert.That(_events.Single(e => e.Method == ChatHubConstants.MessageSent).Groups, Is.EqualTo(new[] { ChatHubConstants.GetSessionGroup(_aliceSession) })); _push.Verify(p => p.SendToUsersAsync(It.Is>(ids => ids.SequenceEqual(new[] { _db.Bob })), "Alice", "hello", "chat_messages", $"chat_{_db.ChatId}", It.Is?>(data => data != null && data["messageId"] == message.MessageId.ToString())), Times.Once); } [Test] public async Task GroupMessageExcludesBannedMembersFromSignalRAndPush() { var group = new ChatGroup { Id = Guid.NewGuid(), Name = "group", Description = "" }; _db.Context.ChatGroups.Add(group); foreach (var user in new[] { _db.Alice, _db.Bob, _db.Outsider }) _db.Context.GroupMemberships.Add(new GroupMembership { Id = Guid.NewGuid(), GroupId = group.Id, UserId = user, IsBanned = user == _db.Outsider }); _db.Context.SaveChanges(); var message = Message(); message.RecipientId = group.Id; message.RecipientType = RecipientType.Group; await _notifier.NotifyMessageSentAsync(message); await _notifier.DeliverPushAsync(message); Assert.That(_events.Single(e => e.Method == ChatHubConstants.ReceiveMessage).Groups.Length, Is.EqualTo(2)); _push.Verify(p => p.SendToUsersAsync(It.Is>(ids => ids.SequenceEqual(new[] { _db.Bob })), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny?>()), Times.Once); } [Test] public async Task SignalRFailureStillAttemptsPushAndProviderFailureDoesNotFailSavedSend() { _proxy.Setup(p => p.SendCoreAsync(It.IsAny(), It.IsAny(), It.IsAny())) .ThrowsAsync(new InvalidOperationException("offline")); _push.Setup(p => p.SendToUsersAsync(It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny?>())) .ThrowsAsync(new InvalidOperationException("provider unavailable")); await _notifier.NotifyMessageSentAsync(Message()); Assert.That(await _notifier.DeliverPushAsync(Message()), Is.False); _push.Verify(p => p.SendToUsersAsync(It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny?>()), Times.Once); } [Test] public async Task ReadNotificationReachesReaderAndAuthorDevices() { await _notifier.NotifyChatReadAsync(new ChatReadResponse { ChatId = _db.ChatId, ReaderId = _db.Bob, RecipientType = RecipientType.User }); Assert.That(_events.Single().Method, Is.EqualTo(ChatHubConstants.ChatRead)); Assert.That(_events.Single().Groups, Is.EquivalentTo(new[] { ChatHubConstants.GetSessionGroup(_aliceSession), ChatHubConstants.GetSessionGroup(_bobSession) })); } [Test] public async Task ReactionChangesReachBothParticipantsActiveDevices() { await _notifier.NotifyMessageReactionsChangedAsync(new MessageReactionsChangedResponse { MessageId = Guid.NewGuid(), RecipientId = _db.ChatId, RecipientType = RecipientType.User, ActorId = _db.Bob }); Assert.That(_events.Single().Method, Is.EqualTo(ChatHubConstants.MessageReactionsChanged)); Assert.That(_events.Single().Groups, Is.EquivalentTo(new[] { ChatHubConstants.GetSessionGroup(_aliceSession), ChatHubConstants.GetSessionGroup(_bobSession) })); } [Test] public async Task ChannelPolicyChangesExcludeBannedMembers() { var group = new ChatGroup { Id = Guid.NewGuid(), Name = "channel", Description = "", IsChannel = true }; _db.Context.ChatGroups.Add(group); foreach (var user in new[] { _db.Alice, _db.Bob, _db.Outsider }) _db.Context.GroupMemberships.Add(new GroupMembership { Id = Guid.NewGuid(), GroupId = group.Id, UserId = user, IsBanned = user == _db.Outsider }); await _db.Context.SaveChangesAsync(); await _notifier.NotifyChannelReactionPolicyChangedAsync(new ChannelReactionPolicyResponse { GroupId = group.Id }); Assert.That(_events.Single().Method, Is.EqualTo(ChatHubConstants.ChannelReactionPolicyChanged)); Assert.That(_events.Single().Groups, Is.EquivalentTo(new[] { ChatHubConstants.GetSessionGroup(_aliceSession), ChatHubConstants.GetSessionGroup(_bobSession) })); } private Guid AddSession(Guid userId, bool revoked = false) { var session = new UserSession { UserId = userId, RefreshTokenHash = Guid.NewGuid().ToString(), IsRevoked = revoked, ExpiresAt = DateTime.UtcNow.AddDays(1) }; _db.Context.UserSessions.Add(session); _db.Context.SaveChanges(); return session.Id; } private UserMessageResponse Message() => new() { MessageId = Guid.NewGuid(), SenderId = _db.Alice, RecipientId = _db.ChatId, RecipientType = RecipientType.User, EncryptedContent = "hello" }; }