diff --git a/Tests/WebSocketTestClient.cs b/Tests/WebSocketTestClient.cs new file mode 100644 index 0000000..65c9a44 --- /dev/null +++ b/Tests/WebSocketTestClient.cs @@ -0,0 +1,56 @@ +using System.Text.Json; +using lib; +using Websocket.Client; + +namespace Tests +{ + public class WebSocketTestClient + { + public readonly WebsocketClient Client; + public readonly List ReceivedMessages = []; + + public WebSocketTestClient(string? url = null) + { + Client = url == null ? new WebsocketClient(new Uri("ws://localhost:" + (Environment.GetEnvironmentVariable("FULLSTACK_API_PORT") ?? "8181"))) : new WebsocketClient(new Uri(url)); + Client.MessageReceived.Subscribe((Action) (msg => + { + BaseDto baseDto = JsonSerializer.Deserialize(msg.Text); + lock (ReceivedMessages) + ReceivedMessages.Add(baseDto); + })); + } + + public async Task ConnectAsync() + { + await Client.Start(); + if (!Client.IsRunning) + throw new Exception("Could not start client!"); + return this; + } + + public void Send(T dto) where T : BaseDto + { + Client.Send(JsonSerializer.Serialize(dto)); + } + + public async Task DoAndAssert(T? action = null, Func, bool>? condition = null) where T : BaseDto + { + if ((object) (T) action != null) + Send(action); + if (condition != null) + { + DateTime startTime = DateTime.UtcNow; + while (DateTime.UtcNow - startTime < TimeSpan.FromSeconds(10.0)) + { + lock (ReceivedMessages) + { + if (condition(ReceivedMessages)) + return; + } + await Task.Delay(100); + } + throw new TimeoutException("Condition not met: "); + } + } + } +} \ No newline at end of file diff --git a/Tests/WebSocketTestClientExtension.cs b/Tests/WebSocketTestClientExtension.cs deleted file mode 100644 index 0b381d7..0000000 --- a/Tests/WebSocketTestClientExtension.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System.Text.Json; -using api.Events.Global; -using lib; -using Websocket.Client; - -namespace Tests; - -public static class WebSocketTestClientExtension -{ - public static void SubscribeToErrors(this WebSocketTestClient client) - { - client.Client.MessageReceived.Subscribe(msg => - { - var baseDto = JsonSerializer.Deserialize(msg.Text); - if (baseDto is ServerSendsErrorMessage errorMessage) - { - Console.WriteLine(errorMessage.Error); - } - }); - } -} \ No newline at end of file