using System.CommandLine;
using ZB.MOM.WW.ScadaBridge.CLI;
using ZB.MOM.WW.ScadaBridge.CLI.Commands;
namespace ZB.MOM.WW.ScadaBridge.CLI.Tests;
/// CLI-5 (atomic bundle export), CLI-6 (user input errors) and CLI-7 (re-subscribe retry).
[Collection("Console")]
public class CliInputAndExportTests : IDisposable
{
private readonly string _dir = Directory.CreateDirectory(
Path.Combine(Path.GetTempPath(), $"cli-wp7-{Guid.NewGuid():N}")).FullName;
/// Removes the temp directory.
public void Dispose() => Directory.Delete(_dir, recursive: true);
// ---- CLI-5 ---------------------------------------------------------
/// Verifies a size mismatch leaves an existing good bundle intact and no temp file behind.
[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(() => BundleCommands.StreamBase64ToFile(payload, target, expectedBytes: 99));
Assert.Equal("last week's good bundle", File.ReadAllText(target));
Assert.Equal([target], Directory.GetFileSystemEntries(_dir));
}
/// Verifies an undecodable payload leaves an existing file intact and no temp file behind.
[Fact]
public void StreamBase64ToFile_InvalidBase64_KeepsExistingFileAndCleansTemp()
{
var target = Path.Combine(_dir, "bundle.scadabundle");
File.WriteAllText(target, "good");
Assert.Throws(() => BundleCommands.StreamBase64ToFile("!!!not base64!!!", target, 3));
Assert.Equal("good", File.ReadAllText(target));
Assert.Equal([target], Directory.GetFileSystemEntries(_dir));
}
/// Verifies a matching size replaces the destination.
[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));
}
/// Verifies the up-front output path probe.
[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 ---------------------------------------------------------
/// Verifies malformed or non-object trigger config is a clean failure, not a thrown exception.
/// The --trigger-config value.
[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); }
}
/// Verifies the real script-add command exits 1 on malformed trigger config without contacting a server.
/// A task that represents the asynchronous operation.
[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("--url") { Recursive = true };
var f = new Option("--format") { Recursive = true };
var user = new Option("--username") { Recursive = true };
var pw = new Option("--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 ---------------------------------------------------------
/// Verifies a re-subscribe that fails twice and then succeeds is retried to success.
/// A task that represents the asynchronous operation.
[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);
}
/// Verifies that a persistent re-subscribe failure is reported to the caller after bounded attempts.
/// A task that represents the asynchronous operation.
[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);
}
/// Verifies cancellation during re-subscribe is not reported as a failure.
/// A task that represents the asynchronous operation.
[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);
}
}