using System.Net; using System.Net.Sockets; using System.Text; namespace ZB.MOM.WW.ScadaBridge.CLI.Tests; /// /// Single-request fake management endpoint: accepts one connection, records the request line /// and body, and answers with a fixed status and body. The CLI tests are pinned to HTTP Basic /// () so one accepted socket is the whole conversation. /// internal static class FakeManagementServer { /// Runs against a one-shot fake server. /// HTTP status line text, e.g. 200 OK. /// The response body (may be empty). /// Receives the base URL; returns the CLI exit code. /// The exit code and the request body the server saw. public static async Task<(int Exit, string RequestBody)> RunAsync( string status, string responseBody, Func> invoke) { var listener = new TcpListener(IPAddress.Loopback, 0); listener.Start(); try { var port = ((IPEndPoint)listener.LocalEndpoint).Port; var server = Task.Run(async () => { using var client = await listener.AcceptTcpClientAsync(); await using var stream = client.GetStream(); using var reader = new StreamReader(stream, Encoding.UTF8, leaveOpen: true); await reader.ReadLineAsync(); var length = 0; while (await reader.ReadLineAsync() is { Length: > 0 } header) if (header.StartsWith("Content-Length:", StringComparison.OrdinalIgnoreCase)) length = int.Parse(header.Split(':')[1]); var buffer = new char[length]; if (length > 0) await reader.ReadBlockAsync(buffer, 0, length); var body = Encoding.UTF8.GetBytes(responseBody); var head = Encoding.ASCII.GetBytes( $"HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {body.Length}\r\nConnection: close\r\n\r\n"); await stream.WriteAsync(head); await stream.WriteAsync(body); return new string(buffer); }); var exit = await invoke($"http://127.0.0.1:{port}"); var requestBody = await server.WaitAsync(TimeSpan.FromSeconds(5)); return (exit, requestBody); } finally { listener.Stop(); } } }