using AyCode.Core.Extensions; using AyCode.Services.SignalRs; using MessagePack; using MessagePack.Resolvers; namespace AyCode.Services.Server.Tests.SignalRs; /// /// Captured sent message for assertions. /// public record SentMessage( int MessageTag, ISignalRMessage Message, int? RequestId, SendTarget Target, string? TargetId = null) { public SignalResponseDataMessage? AsDataResponse => Message as SignalResponseDataMessage; } /// /// Target of the sent message. /// public enum SendTarget { Caller, Client, Others, All, User, Group } /// /// Helper methods for creating SignalR test messages. /// public static class SignalRTestHelper { private static readonly MessagePackSerializerOptions MessagePackOptions = ContractlessStandardResolver.Options; public static byte[] CreatePrimitiveParamsMessage(params object[] values) { var idMessage = new IdMessage(values); var postMessage = new SignalPostJsonDataMessage(idMessage); return MessagePackSerializer.Serialize(postMessage, MessagePackOptions); } public static byte[] CreateSinglePrimitiveMessage(T value) where T : notnull => CreatePrimitiveParamsMessage(value); public static byte[] CreateComplexObjectMessage(T obj) { var json = obj.ToJson(); var postMessage = new SignalPostJsonDataMessage(json); return MessagePackSerializer.Serialize(postMessage, MessagePackOptions); } public static byte[] CreateEmptyMessage() { var postMessage = new SignalPostJsonDataMessage(); return MessagePackSerializer.Serialize(postMessage, MessagePackOptions); } public static T? GetResponseData(SentMessage sentMessage) { if (sentMessage.Message is SignalResponseDataMessage dataResponse && dataResponse.ResponseData != null) return dataResponse.GetResponseData(); return default; } public static void AssertSuccessResponse(SentMessage sentMessage, int expectedTag) { if (sentMessage.Message is not SignalResponseDataMessage response) throw new AssertFailedException($"Response is not SignalResponseDataMessage. Type: {sentMessage.Message.GetType().Name}"); if (response.Status != SignalResponseStatus.Success) throw new AssertFailedException($"Expected Success status but got {response.Status}"); if (sentMessage.MessageTag != expectedTag) throw new AssertFailedException($"Expected tag {expectedTag} but got {sentMessage.MessageTag}"); } public static void AssertErrorResponse(SentMessage sentMessage, int expectedTag) { if (sentMessage.Message is not SignalResponseDataMessage response) throw new AssertFailedException($"Response is not SignalResponseDataMessage. Type: {sentMessage.Message.GetType().Name}"); if (response.Status != SignalResponseStatus.Error) throw new AssertFailedException($"Expected Error status but got {response.Status}"); if (sentMessage.MessageTag != expectedTag) throw new AssertFailedException($"Expected tag {expectedTag} but got {sentMessage.MessageTag}"); } }