|
| 1 | +/* |
| 2 | + * COPYRIGHT: See COPYING in the top level directory |
| 3 | + * PROJECT: CommunicationTests |
| 4 | + * FILE: SimpleLogServerTests.cs |
| 5 | + * PURPOSE: Simple Log Server Tests |
| 6 | + * PROGRAMMER: Peter Geinitz (Wayfarer) |
| 7 | + */ |
| 8 | + |
| 9 | +using System.Net.Sockets; |
| 10 | +using System.Text; |
| 11 | +using Communication; |
| 12 | +using Communication.Interfaces; |
| 13 | + |
| 14 | +namespace CommunicationTests |
| 15 | +{ |
| 16 | + [TestClass] |
| 17 | + public class SimpleLogServerTests |
| 18 | + { |
| 19 | + // Use a random high port to avoid conflicts |
| 20 | + private const int TestPort = 55123; |
| 21 | + |
| 22 | + /// <summary> |
| 23 | + /// Actions the constructor should receive and process message. |
| 24 | + /// </summary> |
| 25 | + [TestMethod] |
| 26 | + public async Task ActionConstructor_ShouldReceiveAndProcessMessage() |
| 27 | + { |
| 28 | + // 1. Setup a TaskCompletionSource. This acts as our "Flag". |
| 29 | + // When the server gets a message, it sets this flag. |
| 30 | + var messageReceivedSignal = new TaskCompletionSource<string>(TaskCreationOptions.RunContinuationsAsynchronously); |
| 31 | + |
| 32 | + using (var server = new SimpleLogServer(TestPort, (msg) => |
| 33 | + { |
| 34 | + // Verify we aren't setting it twice |
| 35 | + messageReceivedSignal.TrySetResult(msg); |
| 36 | + })) |
| 37 | + { |
| 38 | + // 2. Start the Server |
| 39 | + server.Start(); |
| 40 | + |
| 41 | + // 3. Send the message with a "Retry Policy" |
| 42 | + // We try to connect 5 times. If the server is slow to start, this handles it. |
| 43 | + bool connected = await TrySendTcpMessageAsync(TestPort, "Hello World!"); |
| 44 | + Assert.IsTrue(connected, "Could not connect to the server. It might not have started in time."); |
| 45 | + |
| 46 | + // 4. Wait for the result with a TIMEOUT |
| 47 | + // If the signal isn't set in 2 seconds, we force a failure. |
| 48 | + // This prevents the "Endless Run". |
| 49 | + var completedTask = await Task.WhenAny(messageReceivedSignal.Task, Task.Delay(2000)); |
| 50 | + |
| 51 | + if (completedTask != messageReceivedSignal.Task) |
| 52 | + { |
| 53 | + Assert.Fail("Test Timed Out: Server accepted connection but never processed the message."); |
| 54 | + } |
| 55 | + |
| 56 | + Assert.AreEqual("Hello World!", messageReceivedSignal.Task.Result); |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + /// <summary> |
| 61 | + /// Tries the send TCP message asynchronous. |
| 62 | + /// </summary> |
| 63 | + /// <param name="port">The port.</param> |
| 64 | + /// <param name="message">The message.</param> |
| 65 | + /// <returns>Message Status.</returns> |
| 66 | + private async Task<bool> TrySendTcpMessageAsync(int port, string message) |
| 67 | + { |
| 68 | + for (int i = 0; i < 5; i++) |
| 69 | + { |
| 70 | + try |
| 71 | + { |
| 72 | + using (var client = new TcpClient()) |
| 73 | + { |
| 74 | + // Try to connect |
| 75 | + await client.ConnectAsync("127.0.0.1", port); |
| 76 | + |
| 77 | + using (var stream = client.GetStream()) |
| 78 | + { |
| 79 | + // Important: Add NewLine (\n) so ReadLineAsync fires! |
| 80 | + byte[] data = Encoding.UTF8.GetBytes(message + Environment.NewLine); |
| 81 | + await stream.WriteAsync(data, 0, data.Length); |
| 82 | + await stream.FlushAsync(); |
| 83 | + } |
| 84 | + } |
| 85 | + return true; // Success! |
| 86 | + } |
| 87 | + catch (SocketException) |
| 88 | + { |
| 89 | + // Server not ready yet? Wait 100ms and try again. |
| 90 | + await Task.Delay(100); |
| 91 | + } |
| 92 | + } |
| 93 | + return false; // Failed after 5 attempts |
| 94 | + } |
| 95 | + |
| 96 | + /// <summary> |
| 97 | + /// Interfaces the constructor should use processor class. |
| 98 | + /// </summary> |
| 99 | + [TestMethod] |
| 100 | + public async Task InterfaceConstructor_ShouldUseProcessorClass() |
| 101 | + { |
| 102 | + // Arrange |
| 103 | + var fakeProcessor = new FakeLogProcessor(); |
| 104 | + var port = TestPort + 1; |
| 105 | + |
| 106 | + // Create server using the INTERFACE constructor |
| 107 | + using (var server = new SimpleLogServer(port, fakeProcessor)) |
| 108 | + { |
| 109 | + // Act |
| 110 | + server.Start(); |
| 111 | + |
| 112 | + // FIX: Use 'TrySendTcpMessageAsync' (Retry Logic) instead of 'SendTcpMessageAsync' |
| 113 | + // We also check the boolean result to ensure connection happened. |
| 114 | + bool connected = await TrySendTcpMessageAsync(port, "Hello from Class!"); |
| 115 | + Assert.IsTrue(connected, "Could not connect to the server (Timeout)."); |
| 116 | + |
| 117 | + // Wait for the processor to get the message (Polling with timeout) |
| 118 | + string received = null; |
| 119 | + for (var i = 0; i < 20; i++) // Try for 2 seconds (20 * 100ms) |
| 120 | + { |
| 121 | + if (fakeProcessor.LastMessage != null) |
| 122 | + { |
| 123 | + received = fakeProcessor.LastMessage; |
| 124 | + break; |
| 125 | + } |
| 126 | + await Task.Delay(100); |
| 127 | + } |
| 128 | + |
| 129 | + // Assert |
| 130 | + Assert.IsNotNull(received, "Message was never received by the processor."); |
| 131 | + Assert.AreEqual("Hello from Class!", received); |
| 132 | + } |
| 133 | + } |
| 134 | + |
| 135 | + /// <summary> |
| 136 | + /// Servers the should disconnect slow clients. |
| 137 | + /// </summary> |
| 138 | + [TestMethod] |
| 139 | + public async Task Server_ShouldDisconnect_SlowClients() |
| 140 | + { |
| 141 | + // Arrange |
| 142 | + int port = 55150; |
| 143 | + using (var server = new SimpleLogServer(port, msg => { })) |
| 144 | + { |
| 145 | + server.Start(); |
| 146 | + await Task.Delay(100); |
| 147 | + |
| 148 | + using (var client = new TcpClient()) |
| 149 | + { |
| 150 | + await client.ConnectAsync("127.0.0.1", port); |
| 151 | + using (var stream = client.GetStream()) |
| 152 | + { |
| 153 | + // Act: Send data WITHOUT a newline |
| 154 | + byte[] data = Encoding.UTF8.GetBytes("I am a bad client..."); |
| 155 | + await stream.WriteAsync(data, 0, data.Length); |
| 156 | + |
| 157 | + // Don't send \n. Just wait. |
| 158 | + // The server should cut us off after 5 seconds. |
| 159 | + |
| 160 | + // Assert: Try to read from the stream. |
| 161 | + // If the server disconnects us, ReadAsync returns 0. |
| 162 | + byte[] buffer = new byte[10]; |
| 163 | + int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length); |
| 164 | + |
| 165 | + // If bytesRead is 0, it means the server closed the connection. |
| 166 | + Assert.AreEqual(0, bytesRead, "Server should have closed the connection due to timeout."); |
| 167 | + } |
| 168 | + } |
| 169 | + } |
| 170 | + } |
| 171 | + |
| 172 | + /// <inheritdoc /> |
| 173 | + /// <summary> |
| 174 | + /// Helper: A Fake Processor for testing |
| 175 | + /// </summary> |
| 176 | + /// <seealso cref="Communication.Interfaces.ILogProcessor" /> |
| 177 | + private class FakeLogProcessor : ILogProcessor |
| 178 | + { |
| 179 | + /// <summary> |
| 180 | + /// Gets or sets the last message. |
| 181 | + /// </summary> |
| 182 | + /// <value> |
| 183 | + /// The last message. |
| 184 | + /// </value> |
| 185 | + public string LastMessage { get; private set; } |
| 186 | + |
| 187 | + /// <summary> |
| 188 | + /// Processes the received message (e.g., save to DB, log to file). |
| 189 | + /// </summary> |
| 190 | + /// <param name="message">The message received from the client.</param> |
| 191 | + /// <returns>Message Status.</returns> |
| 192 | + public Task ProcessMessageAsync(string message) |
| 193 | + { |
| 194 | + LastMessage = message; |
| 195 | + return Task.CompletedTask; |
| 196 | + } |
| 197 | + } |
| 198 | + } |
| 199 | +} |
0 commit comments