47a7c0dde4
- cached-call retry|discard and data-connection certs list|trust|remove exit 1 when the relayed record carries success:false - bundle export probes the output path first, writes a temp file, compares the byte count, then moves it into place - bodyless / textless HTTP errors report 'HTTP <status> <reason>'; bad --trigger-config, sms update, unreadable bundle file and out-of-range --since give the JSON error envelope - numeric alarm setpoint options and --from/--to date options parse with the invariant culture (de-DE test); offset-less dates are UTC - audit export gets --timeout-seconds (default 600) for both the headers wait and the mid-stream idle deadline - debug stream retries a failed re-subscribe and exits 1 with SUBSCRIBE_FAILED if it cannot recover
167 lines
7.2 KiB
C#
167 lines
7.2 KiB
C#
using System.CommandLine;
|
|
using ZB.MOM.WW.ScadaBridge.CLI;
|
|
using ZB.MOM.WW.ScadaBridge.CLI.Commands;
|
|
|
|
namespace ZB.MOM.WW.ScadaBridge.CLI.Tests;
|
|
|
|
/// <summary>CLI-5 (atomic bundle export), CLI-6 (user input errors) and CLI-7 (re-subscribe retry).</summary>
|
|
[Collection("Console")]
|
|
public class CliInputAndExportTests : IDisposable
|
|
{
|
|
private readonly string _dir = Directory.CreateDirectory(
|
|
Path.Combine(Path.GetTempPath(), $"cli-wp7-{Guid.NewGuid():N}")).FullName;
|
|
|
|
/// <summary>Removes the temp directory.</summary>
|
|
public void Dispose() => Directory.Delete(_dir, recursive: true);
|
|
|
|
// ---- CLI-5 ---------------------------------------------------------
|
|
|
|
/// <summary>Verifies a size mismatch leaves an existing good bundle intact and no temp file behind.</summary>
|
|
[Fact]
|
|
public void StreamBase64ToFile_SizeMismatch_KeepsExistingFileAndCleansTemp()
|
|
{
|
|
var target = Path.Combine(_dir, "bundle.scadabundle");
|
|
File.WriteAllText(target, "last week's good bundle");
|
|
var payload = Convert.ToBase64String(new byte[] { 1, 2, 3, 4 });
|
|
|
|
Assert.Throws<InvalidDataException>(() => BundleCommands.StreamBase64ToFile(payload, target, expectedBytes: 99));
|
|
|
|
Assert.Equal("last week's good bundle", File.ReadAllText(target));
|
|
Assert.Equal([target], Directory.GetFileSystemEntries(_dir));
|
|
}
|
|
|
|
/// <summary>Verifies an undecodable payload leaves an existing file intact and no temp file behind.</summary>
|
|
[Fact]
|
|
public void StreamBase64ToFile_InvalidBase64_KeepsExistingFileAndCleansTemp()
|
|
{
|
|
var target = Path.Combine(_dir, "bundle.scadabundle");
|
|
File.WriteAllText(target, "good");
|
|
|
|
Assert.Throws<FormatException>(() => BundleCommands.StreamBase64ToFile("!!!not base64!!!", target, 3));
|
|
|
|
Assert.Equal("good", File.ReadAllText(target));
|
|
Assert.Equal([target], Directory.GetFileSystemEntries(_dir));
|
|
}
|
|
|
|
/// <summary>Verifies a matching size replaces the destination.</summary>
|
|
[Fact]
|
|
public void StreamBase64ToFile_MatchingSize_ReplacesFile()
|
|
{
|
|
var target = Path.Combine(_dir, "bundle.scadabundle");
|
|
File.WriteAllText(target, "old");
|
|
var bytes = new byte[] { 9, 8, 7 };
|
|
|
|
var written = BundleCommands.StreamBase64ToFile(Convert.ToBase64String(bytes), target, expectedBytes: 3);
|
|
|
|
Assert.Equal(3, written);
|
|
Assert.Equal(bytes, File.ReadAllBytes(target));
|
|
Assert.Equal([target], Directory.GetFileSystemEntries(_dir));
|
|
}
|
|
|
|
/// <summary>Verifies the up-front output path probe.</summary>
|
|
[Fact]
|
|
public void TryProbeOutputPath_RejectsMissingDirectoryAndDirectoryTargets()
|
|
{
|
|
Assert.True(BundleCommands.TryProbeOutputPath(Path.Combine(_dir, "ok.bin"), out _));
|
|
Assert.Empty(Directory.GetFileSystemEntries(_dir));
|
|
|
|
Assert.False(BundleCommands.TryProbeOutputPath(Path.Combine(_dir, "nope", "ok.bin"), out var missing));
|
|
Assert.Contains("does not exist", missing);
|
|
|
|
Assert.False(BundleCommands.TryProbeOutputPath(_dir, out var isDir));
|
|
Assert.Contains("directory", isDir);
|
|
}
|
|
|
|
// ---- CLI-6 ---------------------------------------------------------
|
|
|
|
/// <summary>Verifies malformed or non-object trigger config is a clean failure, not a thrown exception.</summary>
|
|
/// <param name="json">The --trigger-config value.</param>
|
|
[Theory]
|
|
[InlineData("{not json")]
|
|
[InlineData("[1,2]")]
|
|
public void TryInjectAnalysisKind_BadConfig_ReturnsFalseWithEnvelope(string json)
|
|
{
|
|
var originalErr = Console.Error;
|
|
var err = new StringWriter();
|
|
Console.SetError(err);
|
|
try
|
|
{
|
|
Assert.False(TriggerConfigJson.TryInjectAnalysisKind(json, null, out var result));
|
|
Assert.Null(result);
|
|
Assert.Contains("INVALID_ARGUMENT", err.ToString());
|
|
}
|
|
finally { Console.SetError(originalErr); }
|
|
}
|
|
|
|
/// <summary>Verifies the real script-add command exits 1 on malformed trigger config without contacting a server.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task TemplateScriptAdd_MalformedTriggerConfig_ExitsOneCleanly()
|
|
{
|
|
var originalErr = Console.Error;
|
|
var originalOut = Console.Out;
|
|
Console.SetError(TextWriter.Null);
|
|
Console.SetOut(TextWriter.Null);
|
|
try
|
|
{
|
|
var root = new RootCommand();
|
|
var u = new Option<string>("--url") { Recursive = true };
|
|
var f = new Option<string>("--format") { Recursive = true };
|
|
var user = new Option<string>("--username") { Recursive = true };
|
|
var pw = new Option<string>("--password") { Recursive = true };
|
|
root.Add(u); root.Add(f); root.Add(user); root.Add(pw);
|
|
root.Add(TemplateCommands.Build(u, f, user, pw));
|
|
var exit = await root.Parse([
|
|
"template", "script", "add", "--template-id", "1", "--name", "S", "--code", "return 1;",
|
|
"--trigger-type", "ValueChange", "--trigger-config", "{oops",
|
|
"--url", "http://127.0.0.1:1", "--username", "t", "--password", "t"]).InvokeAsync();
|
|
Assert.Equal(1, exit);
|
|
}
|
|
finally { Console.SetError(originalErr); Console.SetOut(originalOut); }
|
|
}
|
|
|
|
// ---- CLI-7 ---------------------------------------------------------
|
|
|
|
/// <summary>Verifies a re-subscribe that fails twice and then succeeds is retried to success.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task Resubscribe_TransientFailures_AreRetried()
|
|
{
|
|
var attempts = 0;
|
|
var failure = await DebugStreamHelpers.ResubscribeWithRetryAsync(
|
|
() => ++attempts < 3 ? Task.FromException(new InvalidOperationException("not ready")) : Task.CompletedTask,
|
|
_ => TimeSpan.Zero, (_, _) => { }, CancellationToken.None);
|
|
|
|
Assert.Null(failure);
|
|
Assert.Equal(3, attempts);
|
|
}
|
|
|
|
/// <summary>Verifies that a persistent re-subscribe failure is reported to the caller after bounded attempts.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task Resubscribe_PersistentFailure_IsReturnedAfterBoundedAttempts()
|
|
{
|
|
var attempts = 0;
|
|
var failure = await DebugStreamHelpers.ResubscribeWithRetryAsync(
|
|
() => { attempts++; return Task.FromException(new InvalidOperationException("rejected")); },
|
|
_ => TimeSpan.Zero, (_, _) => { }, CancellationToken.None);
|
|
|
|
Assert.NotNull(failure);
|
|
Assert.Equal("rejected", failure!.Message);
|
|
Assert.Equal(DebugStreamHelpers.ResubscribeAttempts, attempts);
|
|
}
|
|
|
|
/// <summary>Verifies cancellation during re-subscribe is not reported as a failure.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task Resubscribe_Cancelled_IsNotAFailure()
|
|
{
|
|
using var cts = new CancellationTokenSource();
|
|
cts.Cancel();
|
|
var failure = await DebugStreamHelpers.ResubscribeWithRetryAsync(
|
|
() => Task.FromCanceled(cts.Token), _ => TimeSpan.Zero, (_, _) => { }, cts.Token);
|
|
|
|
Assert.Null(failure);
|
|
}
|
|
}
|