513fa1aa16
Comment/XML-doc changes only: - add summaries to ~10k test methods, fixtures, fakes and helpers (+ <param> on theories, <returns> on async Task methods, <inheritdoc/> on interface implementations the checker can resolve) - strip ~2.6k project-tracking references (WP*, P*-*, row-NN, Task N, #NN, Component-0NN) from comments, keeping the explanatory text; reword false positives in comments only - real docs on fakes implementing BCL/library interfaces (IDisposable, ILogger, IOptionsMonitor, IAsyncLifetime) - reword the last 5 src/ false positives (CWE-1236, failures-1, year-0001, M365) Only non-comment edits: four one-line nested classes split across lines so members can carry docs. Build 0 errors / 0 warnings.
272 lines
11 KiB
C#
272 lines
11 KiB
C#
using System.Diagnostics;
|
|
using System.Net;
|
|
using System.Net.Sockets;
|
|
using System.Text;
|
|
using ZB.MOM.WW.ScadaBridge.CLI;
|
|
|
|
namespace ZB.MOM.WW.ScadaBridge.CLI.Tests;
|
|
|
|
/// <summary>
|
|
/// Regression tests for <see cref="ManagementHttpClient.SendCommandAsync"/>
|
|
/// (success, error-body parsing, connection-failure, and timeout paths), which were previously untested.
|
|
/// Uses a stub <see cref="HttpMessageHandler"/> so no live server is required.
|
|
/// </summary>
|
|
public class ManagementHttpClientTests
|
|
{
|
|
private sealed class StubHandler : HttpMessageHandler
|
|
{
|
|
private readonly Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> _responder;
|
|
|
|
/// <summary>Creates a handler that always answers with the given status code and JSON body.</summary>
|
|
/// <param name="status">The HTTP status code to return.</param>
|
|
/// <param name="body">The JSON response body to return.</param>
|
|
public StubHandler(HttpStatusCode status, string body)
|
|
: this((_, _) => Task.FromResult(new HttpResponseMessage(status)
|
|
{
|
|
Content = new StringContent(body, Encoding.UTF8, "application/json"),
|
|
}))
|
|
{
|
|
}
|
|
|
|
/// <summary>Creates a handler that delegates every request to the supplied responder.</summary>
|
|
/// <param name="responder">The delegate that produces the response for each request.</param>
|
|
public StubHandler(Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> responder)
|
|
{
|
|
_responder = responder;
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
protected override Task<HttpResponseMessage> SendAsync(
|
|
HttpRequestMessage request, CancellationToken cancellationToken)
|
|
=> _responder(request, cancellationToken);
|
|
}
|
|
|
|
private static ManagementHttpClient ClientWith(StubHandler handler)
|
|
=> new(new HttpClient(handler), "http://localhost:9001", "user", "pass");
|
|
|
|
/// <summary>Verifies that a successful response is returned as a success result carrying the JSON data.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task SendCommandAsync_Success_ReturnsJsonData()
|
|
{
|
|
using var client = ClientWith(new StubHandler(HttpStatusCode.OK, "{\"id\":1}"));
|
|
|
|
var response = await client.SendCommandAsync("ListSites", new { }, TimeSpan.FromSeconds(5));
|
|
|
|
Assert.Equal(200, response.StatusCode);
|
|
Assert.Equal("{\"id\":1}", response.JsonData);
|
|
Assert.Null(response.Error);
|
|
Assert.Null(response.ErrorCode);
|
|
}
|
|
|
|
/// <summary>Verifies that an error response body is parsed into the error message and error code.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task SendCommandAsync_ErrorBody_ParsesErrorAndCode()
|
|
{
|
|
using var client = ClientWith(new StubHandler(
|
|
HttpStatusCode.BadRequest, "{\"error\":\"Bad input\",\"code\":\"INVALID_ARGUMENT\"}"));
|
|
|
|
var response = await client.SendCommandAsync("ListSites", new { }, TimeSpan.FromSeconds(5));
|
|
|
|
Assert.Equal(400, response.StatusCode);
|
|
Assert.Null(response.JsonData);
|
|
Assert.Equal("Bad input", response.Error);
|
|
Assert.Equal("INVALID_ARGUMENT", response.ErrorCode);
|
|
}
|
|
|
|
/// <summary>Verifies that a non-JSON error body falls back to the raw body text as the error.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task SendCommandAsync_NonJsonErrorBody_FallsBackToRawBody()
|
|
{
|
|
using var client = ClientWith(new StubHandler(
|
|
HttpStatusCode.BadGateway, "<html>Bad Gateway</html>"));
|
|
|
|
var response = await client.SendCommandAsync("ListSites", new { }, TimeSpan.FromSeconds(5));
|
|
|
|
Assert.Equal(502, response.StatusCode);
|
|
Assert.Equal("<html>Bad Gateway</html>", response.Error);
|
|
Assert.Null(response.ErrorCode);
|
|
}
|
|
|
|
/// <summary>Verifies that a connection failure returns a result with status code zero.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task SendCommandAsync_ConnectionFailure_ReturnsStatusZero()
|
|
{
|
|
using var client = ClientWith(new StubHandler((_, _) =>
|
|
throw new HttpRequestException("connection refused")));
|
|
|
|
var response = await client.SendCommandAsync("ListSites", new { }, TimeSpan.FromSeconds(5));
|
|
|
|
Assert.Equal(0, response.StatusCode);
|
|
Assert.Equal("CONNECTION_FAILED", response.ErrorCode);
|
|
Assert.Contains("connection refused", response.Error);
|
|
}
|
|
|
|
/// <summary>Verifies that a timed-out call returns a 504 status.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task SendCommandAsync_Timeout_Returns504()
|
|
{
|
|
using var client = ClientWith(new StubHandler(async (_, ct) =>
|
|
{
|
|
await Task.Delay(Timeout.Infinite, ct);
|
|
return new HttpResponseMessage(HttpStatusCode.OK);
|
|
}));
|
|
|
|
var response = await client.SendCommandAsync("ListSites", new { }, TimeSpan.FromMilliseconds(50));
|
|
|
|
Assert.Equal(504, response.StatusCode);
|
|
Assert.Equal("TIMEOUT", response.ErrorCode);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// The public <see cref="ManagementHttpClient"/> constructor must leave
|
|
/// <see cref="HttpClient.Timeout"/> INFINITE so the per-call
|
|
/// <see cref="CancellationTokenSource"/> is the single overall deadline — a fixed
|
|
/// client timeout silently truncated every caller with a longer per-call timeout
|
|
/// (<c>deploy site</c>'s 5-minute bulk deploy, the 5-minute <c>bundle</c> calls),
|
|
/// which then printed a fake 504 while the server kept working. The connect phase
|
|
/// is bounded separately on <see cref="SocketsHttpHandler.ConnectTimeout"/>, honoring
|
|
/// the <c>SCADABRIDGE_HTTP_CONNECT_TIMEOUT_SECONDS</c> override — consistent with how
|
|
/// every other CLI setting is environment-overridable (<see cref="CliConfig"/>). Runs
|
|
/// in the shared "Environment" collection (see <see cref="TestCollections"/>) so it
|
|
/// never races another test mutating process-wide environment variables.
|
|
/// </summary>
|
|
[Collection("Environment")]
|
|
public class ManagementHttpClientTimeoutTests
|
|
{
|
|
private const string EnvVar = "SCADABRIDGE_HTTP_CONNECT_TIMEOUT_SECONDS";
|
|
|
|
/// <summary>Verifies that the default constructor leaves the underlying client timeout infinite.</summary>
|
|
[Fact]
|
|
public void DefaultConstructor_LeavesClientTimeoutInfinite()
|
|
{
|
|
using var client = new ManagementHttpClient("http://localhost:9001", "user", "pass");
|
|
|
|
Assert.Equal(Timeout.InfiniteTimeSpan, client.EffectiveTimeout);
|
|
}
|
|
|
|
/// <summary>Verifies that the connect timeout defaults to thirty seconds when the environment variable is unset.</summary>
|
|
[Fact]
|
|
public void ConnectTimeout_DefaultsToThirtySeconds_WhenEnvVarUnset()
|
|
{
|
|
var original = Environment.GetEnvironmentVariable(EnvVar);
|
|
try
|
|
{
|
|
Environment.SetEnvironmentVariable(EnvVar, null);
|
|
|
|
Assert.Equal(TimeSpan.FromSeconds(30), ManagementHttpClient.DefaultConnectTimeout);
|
|
Assert.Equal(TimeSpan.FromSeconds(30), ManagementHttpClient.ResolveConnectTimeout());
|
|
}
|
|
finally
|
|
{
|
|
Environment.SetEnvironmentVariable(EnvVar, original);
|
|
}
|
|
}
|
|
|
|
/// <summary>Verifies that an invalid or non-positive environment value falls back to the default connect timeout.</summary>
|
|
/// <param name="value">The environment variable value to test.</param>
|
|
[Theory]
|
|
[InlineData("0")]
|
|
[InlineData("-5")]
|
|
[InlineData("not-a-number")]
|
|
[InlineData("")]
|
|
public void InvalidOrNonPositiveEnvValue_FallsBackToDefaultConnectTimeout(string value)
|
|
{
|
|
var original = Environment.GetEnvironmentVariable(EnvVar);
|
|
try
|
|
{
|
|
Environment.SetEnvironmentVariable(EnvVar, value);
|
|
|
|
Assert.Equal(TimeSpan.FromSeconds(30), ManagementHttpClient.ResolveConnectTimeout());
|
|
}
|
|
finally
|
|
{
|
|
Environment.SetEnvironmentVariable(EnvVar, original);
|
|
}
|
|
}
|
|
|
|
/// <summary>Verifies that a positive environment variable value overrides the default connect timeout.</summary>
|
|
[Fact]
|
|
public void PositiveEnvValue_OverridesDefaultConnectTimeout()
|
|
{
|
|
var original = Environment.GetEnvironmentVariable(EnvVar);
|
|
try
|
|
{
|
|
Environment.SetEnvironmentVariable(EnvVar, "5");
|
|
|
|
Assert.Equal(TimeSpan.FromSeconds(5), ManagementHttpClient.ResolveConnectTimeout());
|
|
}
|
|
finally
|
|
{
|
|
Environment.SetEnvironmentVariable(EnvVar, original);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// The regression that matters: a per-call timeout LONGER than the old 30 s
|
|
/// client cap must actually be honored. Two calls against the same hanging
|
|
/// local listener — one with a short deadline, one with a longer one — must
|
|
/// time out in that order and at their own deadlines, which is only possible
|
|
/// if <see cref="HttpClient.Timeout"/> is not silently capping both. Uses a
|
|
/// real socket (not the stub handler) so the connect + send path is exercised
|
|
/// end to end, and sub-second deadlines so the test stays fast.
|
|
/// </summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task PerCallTimeoutLongerThanTheOldClientCap_IsHonored()
|
|
{
|
|
// A listener that accepts connections and then never answers: every
|
|
// request hangs until the caller's own deadline fires.
|
|
var listener = new TcpListener(IPAddress.Loopback, 0);
|
|
listener.Start();
|
|
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
|
|
var accepted = new List<TcpClient>();
|
|
var acceptLoop = Task.Run(async () =>
|
|
{
|
|
try
|
|
{
|
|
while (true)
|
|
accepted.Add(await listener.AcceptTcpClientAsync());
|
|
}
|
|
catch (ObjectDisposedException) { /* listener stopped — expected */ }
|
|
catch (SocketException) { /* listener stopped — expected */ }
|
|
});
|
|
|
|
try
|
|
{
|
|
using var client = new ManagementHttpClient($"http://127.0.0.1:{port}", "user", "pass");
|
|
|
|
var shortSw = Stopwatch.StartNew();
|
|
var shortResponse = await client.SendCommandAsync("ListSites", new { }, TimeSpan.FromMilliseconds(300));
|
|
shortSw.Stop();
|
|
|
|
var longSw = Stopwatch.StartNew();
|
|
var longResponse = await client.SendCommandAsync("ListSites", new { }, TimeSpan.FromMilliseconds(1500));
|
|
longSw.Stop();
|
|
|
|
Assert.Equal("TIMEOUT", shortResponse.ErrorCode);
|
|
Assert.Equal("TIMEOUT", longResponse.ErrorCode);
|
|
|
|
// The longer deadline must genuinely outlast the shorter one rather
|
|
// than both being clipped to a single client-wide cap.
|
|
Assert.True(
|
|
longSw.Elapsed > TimeSpan.FromMilliseconds(1000),
|
|
$"1.5 s per-call timeout returned after only {longSw.ElapsedMilliseconds} ms — the client cap truncated it.");
|
|
Assert.True(
|
|
shortSw.Elapsed < TimeSpan.FromMilliseconds(1000),
|
|
$"300 ms per-call timeout took {shortSw.ElapsedMilliseconds} ms.");
|
|
}
|
|
finally
|
|
{
|
|
listener.Stop();
|
|
foreach (var c in accepted) c.Dispose();
|
|
await acceptLoop;
|
|
}
|
|
}
|
|
}
|