using System.CommandLine;
using System.Net;
using System.Net.Sockets;
using System.Text;
using ZB.MOM.WW.ScadaBridge.CLI.Commands;
namespace ZB.MOM.WW.ScadaBridge.CLI.Tests;
public class DeploySiteExitCodeTests
{
/// Verifies that the actual deploy command returns an exit code derived from the success and failure counts in the response.
/// The JSON response body served by the fake management endpoint.
/// The expected process exit code.
/// A task that represents the asynchronous operation.
[Theory]
[InlineData("{\"successCount\":2,\"failureCount\":0}", 0)]
[InlineData("{\"successCount\":1,\"failureCount\":1}", 1)]
[InlineData("{\"unexpected\":true}", 1)]
public async Task DC6_ActualDeployCommandReturnsDomainExitCode(string response, int expected)
{
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.ASCII, leaveOpen: true);
while (await reader.ReadLineAsync() is { Length: > 0 }) { }
var body = Encoding.UTF8.GetBytes(response);
var headers = Encoding.ASCII.GetBytes($"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {body.Length}\r\nConnection: close\r\n\r\n");
await stream.WriteAsync(headers);
await stream.WriteAsync(body);
});
var root = new RootCommand();
var url = new Option("--url") { Recursive = true };
var format = new Option("--format") { Recursive = true };
var user = new Option("--username") { Recursive = true };
var password = new Option("--password") { Recursive = true };
root.Add(url); root.Add(format); root.Add(user); root.Add(password);
root.Add(DeployCommands.Build(url, format, user, password));
var exit = await root.Parse(["deploy", "site", "--site-id", "1", "--url", $"http://127.0.0.1:{port}",
"--username", "test", "--password", "test", "--format", "json"]).InvokeAsync();
await server.WaitAsync(TimeSpan.FromSeconds(5));
Assert.Equal(expected, exit);
}
finally { listener.Stop(); }
}
}