Merge branch 'review/wp7' into review/integration

This commit is contained in:
Joseph Doherty
2026-12-03 10:41:19 -05:00
47 changed files with 1584 additions and 152 deletions
@@ -0,0 +1,166 @@
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);
}
}
@@ -0,0 +1,37 @@
using System.Net;
using ZB.MOM.WW.ScadaBridge.CLI;
namespace ZB.MOM.WW.ScadaBridge.CLI.Tests;
/// <summary>CLI-6: a bodyless or textless HTTP error must still produce a readable message.</summary>
public class ErrorMessageTests
{
/// <summary>Verifies that an empty error body synthesises "HTTP {status} {reason}".</summary>
/// <param name="code">The HTTP status.</param>
/// <param name="body">The response body.</param>
/// <param name="expected">The expected error text.</param>
[Theory]
[InlineData(502, "", "HTTP 502 Bad Gateway")]
[InlineData(307, "", "HTTP 307 Temporary Redirect")]
[InlineData(500, "{\"error\":\"\",\"code\":\"X\"}", "HTTP 500 Internal Server Error")]
[InlineData(400, "{\"error\":\"bad thing\",\"code\":\"BAD\"}", "bad thing")]
[InlineData(400, "plain text", "plain text")]
public void ToErrorResponse_NeverReturnsEmptyError(int code, string body, string expected)
{
using var response = new HttpResponseMessage((HttpStatusCode)code);
var result = ManagementHttpClient.ToErrorResponse(response, body);
Assert.Equal(expected, result.Error);
Assert.Equal(code, result.StatusCode);
Assert.Null(result.JsonData);
}
/// <summary>Verifies that the server's error code is preserved.</summary>
[Fact]
public void ToErrorResponse_KeepsServerErrorCode()
{
using var response = new HttpResponseMessage(HttpStatusCode.BadRequest);
var result = ManagementHttpClient.ToErrorResponse(response, "{\"error\":\"e\",\"code\":\"BAD\"}");
Assert.Equal("BAD", result.ErrorCode);
}
}
@@ -0,0 +1,53 @@
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace ZB.MOM.WW.ScadaBridge.CLI.Tests;
/// <summary>
/// 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
/// (<see cref="CliTestAssemblySetup"/>) so one accepted socket is the whole conversation.
/// </summary>
internal static class FakeManagementServer
{
/// <summary>Runs <paramref name="invoke"/> against a one-shot fake server.</summary>
/// <param name="status">HTTP status line text, e.g. <c>200 OK</c>.</param>
/// <param name="responseBody">The response body (may be empty).</param>
/// <param name="invoke">Receives the base URL; returns the CLI exit code.</param>
/// <returns>The exit code and the request body the server saw.</returns>
public static async Task<(int Exit, string RequestBody)> RunAsync(
string status, string responseBody, Func<string, Task<int>> 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(); }
}
}
@@ -0,0 +1,112 @@
using System.CommandLine;
using System.Globalization;
using System.Text.Json;
using ZB.MOM.WW.ScadaBridge.CLI.Commands;
namespace ZB.MOM.WW.ScadaBridge.CLI.Tests;
/// <summary>
/// CLI-3: numeric and date options must not depend on the workstation culture. Every test
/// here runs with <c>de-DE</c> as the current culture (comma decimal, day-first dates).
/// </summary>
[Collection("Console")]
public class InvariantCultureOptionTests
{
private static T UnderGerman<T>(Func<T> body)
{
var originalCulture = CultureInfo.CurrentCulture;
var originalUi = CultureInfo.CurrentUICulture;
CultureInfo.CurrentCulture = CultureInfo.CurrentUICulture = new CultureInfo("de-DE");
try { return body(); }
finally { CultureInfo.CurrentCulture = originalCulture; CultureInfo.CurrentUICulture = originalUi; }
}
/// <summary>Verifies a dot-decimal setpoint parses as 80.5 (not 805) under de-DE.</summary>
[Fact]
public void DoubleOption_DotDecimal_ParsesInvariantUnderGerman()
{
var value = UnderGerman(() =>
{
var option = CliOptions.CreateInvariantDoubleOption("--hi", "d");
var cmd = new Command("x") { option };
return cmd.Parse(["--hi", "80.5"]).GetValue(option);
});
Assert.Equal(80.5, value);
}
/// <summary>Verifies that a comma-decimal value is a parse error rather than a silently different number.</summary>
[Theory]
[InlineData("80,5")]
[InlineData("1,000")]
[InlineData("abc")]
[InlineData("NaN")]
public void DoubleOption_NonInvariantText_IsParseError(string text)
{
var errors = UnderGerman(() =>
{
var option = CliOptions.CreateInvariantDoubleOption("--hi", "d");
var cmd = new Command("x") { option };
return cmd.Parse(["--hi", text]).Errors.Count;
});
Assert.NotEqual(0, errors);
}
/// <summary>Verifies that a timestamp with no offset is read as UTC, day/month order invariant, under de-DE.</summary>
[Fact]
public void DateOption_NoOffset_IsUtcAndInvariantUnderGerman()
{
var value = UnderGerman(() =>
{
var option = CliOptions.CreateInvariantDateOption("--from", "d");
var cmd = new Command("x") { option };
return cmd.Parse(["--from", "2026-11-01T00:00:00"]).GetValue(option);
});
Assert.Equal(new DateTimeOffset(2026, 11, 1, 0, 0, 0, TimeSpan.Zero), value);
}
/// <summary>Verifies the actual <c>template alarm add --hi 80.5</c> command stores 80.5 under de-DE.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task TemplateAlarmAdd_Hi_SendsInvariantNumberUnderGerman()
{
var originalCulture = CultureInfo.CurrentCulture;
var originalOut = Console.Out;
CultureInfo.CurrentCulture = CultureInfo.CurrentUICulture = new CultureInfo("de-DE");
Console.SetOut(TextWriter.Null);
try
{
var (exit, body) = await FakeManagementServer.RunAsync("200 OK", "{}", async url =>
{
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));
return await root.Parse([
"template", "alarm", "add", "--template-id", "1", "--name", "A", "--trigger-type", "HiLo",
"--priority", "500", "--attribute", "Temp", "--hi", "80.5", "--lo", "10.25",
"--url", url, "--username", "t", "--password", "t"]).InvokeAsync();
});
Assert.Equal(0, exit);
using var doc = JsonDocument.Parse(body);
var config = doc.RootElement.GetProperty("payload").GetProperty("triggerConfiguration").GetString()!;
using var cfg = JsonDocument.Parse(config);
Assert.Equal(80.5, cfg.RootElement.GetProperty("hi").GetDouble());
Assert.Equal(10.25, cfg.RootElement.GetProperty("lo").GetDouble());
}
finally
{
Console.SetOut(originalOut);
CultureInfo.CurrentCulture = CultureInfo.CurrentUICulture = originalCulture;
}
}
/// <summary>Verifies the audit time spec parser rejects out-of-range relative offsets as FormatException.</summary>
[Theory]
[InlineData("99999999999d")]
[InlineData("2147483647d")]
public void ResolveTimeSpec_OutOfRange_IsFormatException(string spec)
=> Assert.Throws<FormatException>(() => AuditQueryHelpers.ResolveTimeSpec(spec, DateTimeOffset.UtcNow));
}
@@ -0,0 +1,78 @@
using System.CommandLine;
using ZB.MOM.WW.ScadaBridge.CLI.Commands;
namespace ZB.MOM.WW.ScadaBridge.CLI.Tests;
/// <summary>
/// CLI-1: site-relayed commands return their result record as HTTP 200 with the failure in a
/// <c>success</c> flag. The CLI must exit 1 for <c>success:false</c>.
/// </summary>
[Collection("Console")]
public class SuccessFlagExitCodeTests
{
private static RootCommand BuildRoot()
{
var root = new RootCommand();
var url = new Option<string>("--url") { Recursive = true };
var format = new Option<string>("--format") { Recursive = true };
var user = new Option<string>("--username") { Recursive = true };
var password = new Option<string>("--password") { Recursive = true };
root.Add(url); root.Add(format); root.Add(user); root.Add(password);
root.Add(CachedCallCommands.Build(url, format, user, password));
var dc = DataConnectionCommands.Build(url, format, user, password);
ConnectionBrowseCommands.AddTo(dc, url, format, user, password);
root.Add(dc);
return root;
}
/// <summary>Verifies that the shared handler maps the <c>success</c> flag to the exit code.</summary>
/// <param name="json">The response body.</param>
/// <param name="expected">The expected exit code.</param>
[Theory]
[InlineData("{\"correlationId\":\"c\",\"success\":true,\"errorMessage\":null}", 0)]
[InlineData("{\"correlationId\":\"c\",\"success\":false,\"errorMessage\":\"not parked\"}", 1)]
[InlineData("{\"Success\":false,\"Error\":\"one node failed\"}", 1)]
[InlineData("{\"certs\":[]}", 0)]
[InlineData("[1,2]", 0)]
public void HandleSuccessFlagResponse_MapsFlagToExitCode(string json, int expected)
{
var originalOut = Console.Out;
var originalErr = Console.Error;
Console.SetOut(TextWriter.Null);
Console.SetError(TextWriter.Null);
try
{
Assert.Equal(expected, CommandHelpers.HandleSuccessFlagResponse(json, "json"));
}
finally { Console.SetOut(originalOut); Console.SetError(originalErr); }
}
/// <summary>Verifies that each relayed command exits 1 on success:false and 0 on success:true.</summary>
/// <param name="arguments">Command line (without connection options).</param>
/// <param name="response">The response body.</param>
/// <param name="expected">Expected exit code.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
[Theory]
[InlineData("cached-call retry --site-id s --tracked-operation-id 11111111-2222-3333-4444-555555555555", "{\"correlationId\":\"c\",\"success\":false,\"errorMessage\":\"not parked\"}", 1)]
[InlineData("cached-call retry --site-id s --tracked-operation-id 11111111-2222-3333-4444-555555555555", "{\"correlationId\":\"c\",\"success\":true}", 0)]
[InlineData("cached-call discard --site-id s --tracked-operation-id 11111111-2222-3333-4444-555555555555", "{\"correlationId\":\"c\",\"success\":false,\"errorMessage\":\"gone\"}", 1)]
[InlineData("data-connection certs remove --site s --thumbprint AB", "{\"success\":false,\"error\":\"node B unreachable\",\"certs\":null}", 1)]
[InlineData("data-connection certs remove --site s --thumbprint AB", "{\"success\":true,\"error\":null,\"certs\":[]}", 0)]
public async Task RelayedCommand_ExitCodeFollowsSuccessFlag(string arguments, string response, int expected)
{
var originalOut = Console.Out;
var originalErr = Console.Error;
Console.SetOut(TextWriter.Null);
Console.SetError(TextWriter.Null);
try
{
var (exit, _) = await FakeManagementServer.RunAsync("200 OK", response, async url =>
{
var args = arguments.Split(' ').Concat(new[] { "--url", url, "--username", "t", "--password", "t", "--format", "json" }).ToArray();
return await BuildRoot().Parse(args).InvokeAsync();
});
Assert.Equal(expected, exit);
}
finally { Console.SetOut(originalOut); Console.SetError(originalErr); }
}
}
@@ -655,6 +655,27 @@ public class FlowGraphBuilderTests
Assert.Equal(sa.Lifecycle!.Select(r => r.Kind), sb.Lifecycle!.Select(r => r.Kind));
}
/// <summary>
/// CMN-6: the resolve row is written centrally and the submit row at the site; with the site clock
/// ahead, the submit row's timestamp is LATER than the delivery's. The fold must still treat the
/// resolve as terminal, not render the completed operation as Pending.
/// </summary>
[Fact]
public void Fold_WithCrossNodeClockSkew_StillTreatsResolveAsTerminal()
{
var corr = Guid.NewGuid();
var submit = Outbound(AuditChannel.ApiOutbound, AuditKind.CachedSubmit, AuditStatus.Submitted, 2000, corr, "Delmia.Ack", node: "node-a", request: "req");
var resolve = Outbound(AuditChannel.ApiOutbound, AuditKind.CachedResolve, AuditStatus.Delivered, 1000, corr, "Delmia.Ack", node: "central-a", response: "res");
var graph = FlowGraphBuilder.Build([SiteRunRow(20), submit, resolve]);
var step = Assert.Single(graph.Steps, s => s.Kind == FlowStepKind.ApiCall);
Assert.Equal(FlowStepOutcome.Ok, step.Outcome);
Assert.Equal("res", step.OutputJson);
Assert.Equal(["CachedSubmit", "CachedResolve"], step.Lifecycle!.Select(r => r.Kind));
Assert.True(step.DurationMs >= 0);
}
/// <summary>Verifies that a cached step whose submit row is missing is still treated as asynchronous.</summary>
[Fact]
public void CachedStep_WhoseSubmitRowIsMissing_IsStillAsync()
@@ -197,4 +197,16 @@ public class NativeAlarmSourceOverrideCsvParserTests
Assert.Empty(result.Rows);
Assert.Contains(result.Errors, e => e.Contains("Line 2") && e.Contains("MesReportable"));
}
/// <summary>Verifies that one trailing delimiter on every row (a spreadsheet export) is tolerated, header included.</summary>
[Fact]
public void Parse_TrailingCommaOnEveryRow_IsTolerated()
{
const string csv = "SourceName,Connection,SourceReference,Filter,\nPressure,OPC,ns=2;s=P,Active,\n";
var result = NativeAlarmSourceOverrideCsvParser.Parse(csv);
Assert.Empty(result.Errors);
Assert.Equal("Pressure", Assert.Single(result.Rows).SourceName);
}
}
@@ -262,4 +262,39 @@ public class OverrideCsvParserTests
Assert.Equal("a,b", row.Value);
Assert.Equal("Type", row.ElementType);
}
/// <summary>Verifies that one trailing delimiter on every row (a spreadsheet export) is tolerated, header included.</summary>
[Fact]
public void Parse_TrailingCommaOnEveryRow_IsTolerated()
{
const string csv = "AttributeName,Value,ElementType,\nSetpoint,42,Int32,\nName,Pump A,,\n";
var result = OverrideCsvParser.Parse(csv);
Assert.Empty(result.Errors);
Assert.Equal(2, result.Rows.Count);
Assert.Equal("Int32", result.Rows[0].ElementType);
Assert.Null(result.Rows[1].ElementType);
}
/// <summary>Verifies that a two-column file with a trailing comma is tolerated.</summary>
[Fact]
public void Parse_TwoColumnWithTrailingComma_IsTolerated()
{
var result = OverrideCsvParser.Parse("AttributeName,Value,\nSetpoint,42,\n");
Assert.Empty(result.Errors);
Assert.Equal("42", Assert.Single(result.Rows).Value);
}
/// <summary>Verifies that a genuinely wrong column count, or a NON-empty extra column, stays an error.</summary>
[Fact]
public void Parse_ExtraNonEmptyColumn_StillAnError()
{
var result = OverrideCsvParser.Parse("AttributeName,Value\nSetpoint,42,extra\nA,1,,\n");
Assert.Empty(result.Rows);
Assert.Equal(2, result.Errors.Count);
Assert.All(result.Errors, e => Assert.Contains("expected 2 columns", e));
}
}
@@ -0,0 +1,26 @@
using ZB.MOM.WW.ScadaBridge.Commons.Types.Audit;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
namespace ZB.MOM.WW.ScadaBridge.Commons.Tests.Types.Audit;
/// <summary>Review CMN-12: stored enum tokens parse case-insensitively, like the query parsers.</summary>
public class AuditRowProjectionParseEnumTests
{
/// <summary>A mis-cased stored token resolves to its member rather than the fallback.</summary>
/// <param name="stored">The stored token.</param>
[Theory]
[InlineData("DbOutbound")]
[InlineData("dboutbound")]
[InlineData("DBOUTBOUND")]
public void ParseEnum_IsCaseInsensitive(string stored)
=> Assert.Equal(AuditChannel.DbOutbound, AuditRowProjection.ParseEnum(stored, AuditChannel.ApiInbound));
/// <summary>Unknown or empty tokens still fall back.</summary>
/// <param name="stored">The stored token.</param>
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData("NoSuchChannel")]
public void ParseEnum_UnknownFallsBack(string? stored)
=> Assert.Equal(AuditChannel.ApiInbound, AuditRowProjection.ParseEnum(stored, AuditChannel.ApiInbound));
}
@@ -0,0 +1,44 @@
using System.Text.Json;
using ZB.MOM.WW.ScadaBridge.Commons.Types.InboundApi;
namespace ZB.MOM.WW.ScadaBridge.Commons.Tests.Types.InboundApi;
/// <summary>Review CMN-7 (required matching) and CMN-8 (unknown legacy types).</summary>
public class InboundApiSchemaWp7Tests
{
/// <summary>A "required" entry spelled with different casing than the property still makes it required.</summary>
[Fact]
public void Required_MatchesPropertyNamesCaseInsensitively()
{
const string json = """{"type":"object","properties":{"WorkOrders":{"type":"string"},"Other":{"type":"string"}},"required":["workorders"]}""";
var schema = InboundApiSchema.Parse(json)!;
Assert.True(schema.Fields.Single(f => f.Name == "WorkOrders").Required);
Assert.False(schema.Fields.Single(f => f.Name == "Other").Required);
}
/// <summary>A typo'd legacy type is a parse error naming the field and the valid vocabulary.</summary>
/// <param name="legacy">The legacy parameter array.</param>
[Theory]
[InlineData("""[{"name":"Qty","type":"strign"}]""")]
[InlineData("""[{"name":"Items","type":"List","itemType":"intger"}]""")]
public void LegacyArray_UnknownType_ThrowsClearError(string legacy)
{
var ex = Assert.Throws<JsonException>(() => InboundApiSchema.Parse(legacy));
Assert.Contains("unknown", ex.Message);
Assert.Contains("Valid types", ex.Message);
}
/// <summary>Every legacy alias still parses.</summary>
[Fact]
public void LegacyArray_KnownAliases_StillParse()
{
const string legacy = """[{"name":"a","type":"Integer"},{"name":"b","type":"Float"},{"name":"c","type":"DateTime"},{"name":"d","type":"List","itemType":"String"},{"name":"e","type":"Object"},{"name":"f","type":"Boolean"},{"name":"g"}]""";
var schema = InboundApiSchema.Parse(legacy)!;
Assert.Equal(7, schema.Fields.Count);
}
}
@@ -0,0 +1,94 @@
using Microsoft.EntityFrameworkCore;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Repositories;
namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests;
/// <summary>
/// DEP-2: <see cref="DeploymentManagerRepository.ReloadInstanceAsync"/> refreshes an instance a command
/// loaded before it waited for the per-instance operation lock. The competing write goes through
/// <c>ExecuteUpdate</c>/<c>ExecuteDelete</c> so the tracked copy stays stale, as it would under a
/// second DbContext.
/// </summary>
public class ReloadInstanceRepositoryTests : IDisposable
{
private readonly ScadaBridgeDbContext _context = SqliteTestHelper.CreateInMemoryContext();
private readonly DeploymentManagerRepository _repository;
/// <summary>Initializes the repository under test.</summary>
public ReloadInstanceRepositoryTests() => _repository = new DeploymentManagerRepository(_context);
/// <summary>Releases the database context.</summary>
public void Dispose()
{
_context.Database.CloseConnection();
_context.Dispose();
}
private async Task<int> SeedAsync(InstanceState state)
{
var site = new Site("S", "SI-S");
_context.Sites.Add(site);
var template = new Template("T");
_context.Templates.Add(template);
await _context.SaveChangesAsync();
var instance = new Instance("Inst") { SiteId = site.Id, TemplateId = template.Id, State = state };
_context.Instances.Add(instance);
await _context.SaveChangesAsync();
return instance.Id;
}
/// <summary>A tracked entity picks up a state written behind its back.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task ReloadInstanceAsync_Tracked_SeesStateWrittenMeanwhile()
{
var id = await SeedAsync(InstanceState.NotDeployed);
var instance = (await _repository.GetInstanceByIdAsync(id))!;
await _context.Instances.Where(i => i.Id == id)
.ExecuteUpdateAsync(s => s.SetProperty(i => i.State, InstanceState.Enabled));
Assert.Equal(InstanceState.NotDeployed, instance.State); // stale, as in the race
var removed = await _repository.ReloadInstanceAsync(instance);
Assert.False(removed);
Assert.Equal(InstanceState.Enabled, instance.State);
Assert.Equal(EntityState.Unchanged, _context.Entry(instance).State);
}
/// <summary>An untracked entity gets its state re-read.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task ReloadInstanceAsync_Untracked_SeesStateWrittenMeanwhile()
{
var id = await SeedAsync(InstanceState.Enabled);
var instance = await _context.Instances.AsNoTracking().SingleAsync(i => i.Id == id);
await _context.Instances.Where(i => i.Id == id)
.ExecuteUpdateAsync(s => s.SetProperty(i => i.State, InstanceState.Disabled));
var removed = await _repository.ReloadInstanceAsync(instance);
Assert.False(removed);
Assert.Equal(InstanceState.Disabled, instance.State);
}
/// <summary>A row deleted meanwhile is reported as removed, tracked or not.</summary>
/// <param name="tracked">Whether the instance is loaded with tracking.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task ReloadInstanceAsync_RowDeleted_ReportsRemoved(bool tracked)
{
var id = await SeedAsync(InstanceState.Enabled);
var instance = tracked
? (await _repository.GetInstanceByIdAsync(id))!
: await _context.Instances.AsNoTracking().SingleAsync(i => i.Id == id);
await _context.Instances.Where(i => i.Id == id).ExecuteDeleteAsync();
Assert.True(await _repository.ReloadInstanceAsync(instance));
}
}
@@ -1326,6 +1326,84 @@ public class DeploymentServiceTests : TestKit
Assert.Equal(1, serializationCounters.MaxConcurrent);
}
// ── DEP-2: validate the state transition AFTER the operation lock is held ──
/// <summary>
/// A command that waited behind another one must judge the state that command left behind:
/// here the instance was Enabled when loaded, but another Disable finished while this one
/// waited for the lock. Validating the stale copy would send a second Disable to the site.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task DisableInstanceAsync_StateChangedWhileWaitingForLock_FailsTransitionCheckOnFreshState()
{
var instance = new Instance("RaceDisable") { Id = 80, SiteId = 1, State = InstanceState.Enabled };
_repo.GetInstanceByIdAsync(80, Arg.Any<CancellationToken>()).Returns(instance);
// The reload observes what the lock holder committed.
_repo.ReloadInstanceAsync(instance, Arg.Any<CancellationToken>()).Returns(_ =>
{
instance.State = InstanceState.Disabled;
return Task.FromResult(false);
});
using var held = await _lockManager.AcquireAsync("RaceDisable", TimeSpan.FromSeconds(5), CancellationToken.None);
var pending = _service.DisableInstanceAsync(80, "admin");
await Task.Delay(100);
Assert.False(pending.IsCompleted, "the command must wait for the lock before validating");
held.Dispose();
var result = await pending;
// The default _service has no comm actor: reaching the site would throw, so a clean
// failure proves the transition check ran on the fresh Disabled state first.
Assert.True(result.IsFailure);
Assert.Contains("not allowed", result.Error);
}
/// <summary>
/// Instance X was NotDeployed when the Delete loaded it, then a deploy that held the lock left it
/// Enabled. The Delete must take the site round-trip, not the NotDeployed central-only shortcut.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task DeleteInstanceAsync_DeployCompletedWhileWaiting_TearsDownSiteInsteadOfSkippingIt()
{
var instance = new Instance("RaceDelete") { Id = 81, SiteId = 1, State = InstanceState.NotDeployed };
_repo.GetInstanceByIdAsync(81, Arg.Any<CancellationToken>()).Returns(instance);
_repo.ReloadInstanceAsync(instance, Arg.Any<CancellationToken>()).Returns(_ =>
{
instance.State = InstanceState.Enabled;
return Task.FromResult(false);
});
var counters = new ReconcileProbeCounters();
var commActor = Sys.ActorOf(Props.Create(() =>
new ReconcileProbeActor(counters, siteHash: "x", failQuery: false)));
var service = CreateServiceWithCommActor(commActor);
var result = await service.DeleteInstanceAsync(81, "admin");
Assert.True(result.IsSuccess);
await _audit.Received().LogAsync(
"admin", "Delete", "Instance", "81", "RaceDelete",
Arg.Is<object>(o => !o.ToString()!.Contains("SiteRoundTripSkipped")), Arg.Any<CancellationToken>());
}
/// <summary>An instance deleted by another command while this one waited is reported as not found.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task EnableInstanceAsync_InstanceDeletedWhileWaiting_ReturnsNotFound()
{
var instance = new Instance("RaceGone") { Id = 82, SiteId = 1, State = InstanceState.Disabled };
_repo.GetInstanceByIdAsync(82, Arg.Any<CancellationToken>()).Returns(instance);
_repo.ReloadInstanceAsync(instance, Arg.Any<CancellationToken>()).Returns(true);
var result = await _service.EnableInstanceAsync(82, "admin");
Assert.True(result.IsFailure);
Assert.Contains("not found", result.Error);
}
// ── Query-the-site-before-redeploy idempotency ──
/// <summary>
@@ -1106,6 +1106,40 @@ public class InboundScriptExecutorTests
Assert.Equal(0, _executor.AbandonedExecutionCount); // ...and DECREMENTED
}
/// <summary>
/// INB-1: a script that blocks BEFORE its first await (CPU loop, <c>.Result</c> on a helper) used to
/// run inline on the request thread, so the method timeout could not fire until it returned. The
/// request must come back with TIMEOUT at the deadline and the orphan must be counted.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task ScriptBlockingBeforeFirstAwait_StillTimesOutAtTheDeadline()
{
var release = new ManualResetEventSlim();
_executor.RegisterHandler("spin", _ =>
{
release.Wait(TimeSpan.FromSeconds(30)); // synchronous block: no await has happened yet
return Task.FromResult<object?>(1);
});
var method = new ApiMethod("spin", "unused") { Id = 10, TimeoutSeconds = 1 };
var started = System.Diagnostics.Stopwatch.StartNew();
var execution = _executor.ExecuteAsync(
method, new Dictionary<string, object?>(), _route, TimeSpan.FromMilliseconds(200));
var finished = await Task.WhenAny(execution, Task.Delay(TimeSpan.FromSeconds(10)));
Assert.Same(execution, finished); // pre-fix: the call itself never returned until released
var result = await execution;
Assert.False(result.Success);
Assert.Equal("TIMEOUT", result.ErrorCode);
Assert.True(started.Elapsed < TimeSpan.FromSeconds(5), $"took {started.Elapsed}");
Assert.Equal(1, _executor.AbandonedExecutionCount);
release.Set(); // the orphan finishes; its continuation cleans up
await Task.Delay(300);
Assert.Equal(0, _executor.AbandonedExecutionCount);
}
// --- Flow Debugger step logs (design 2026-09-09 D4/D5/D7): the Log global ---
/// <summary>Verifies that a traced run emits one ScriptLog row on the trace sink.</summary>
@@ -257,6 +257,58 @@ public class CookieSessionValidatorTests
Assert.Equal(SessionValidationAction.Reject, result.Action);
}
private static CookieSessionValidator CreateTrackedValidator(
IGroupRoleMapper<string> mapper, TimeProvider clock, SessionActivityTracker tracker) =>
new(mapper, Microsoft.Extensions.Options.Options.Create(Options()), clock,
NullLogger<CookieSessionValidator>.Instance, tracker);
/// <summary>
/// SEC-1: a passive request cannot write the cookie, so an UNCHANGED role refresh is remembered on the
/// node; the next ping (still carrying the old cookie anchors) must not repeat the re-map.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task ValidateAsync_PassiveUnchangedRefresh_IsNotRepeatedOnTheNextPing()
{
var clock = new TestTimeProvider(Start);
var mapping = new RoleMappingResult([Roles.Administrator], [], true);
var mapper = new FakeGroupRoleMapper(mapping);
var sut = CreateTrackedValidator(mapper, clock, new SessionActivityTracker());
var cookie = Session(Start, ["SCADA-Admins"], mapping); // the ticket never changes: passive requests cannot re-issue it
clock.Advance(TimeSpan.FromMinutes(16));
var first = await sut.ValidateAsync(cookie, recordActivity: false);
var second = await sut.ValidateAsync(cookie, recordActivity: false);
clock.Advance(TimeSpan.FromMinutes(14)); // 30 min since login, 14 since the remembered refresh
var third = await sut.ValidateAsync(cookie, recordActivity: false);
Assert.Equal(SessionValidationAction.Replace, first.Action);
Assert.Equal(SessionValidationAction.Keep, second.Action);
Assert.Equal(1, mapper.CallCount);
Assert.Equal(SessionValidationAction.Keep, third.Action);
Assert.Equal(1, mapper.CallCount);
}
/// <summary>A passive refresh that CHANGED the grants is not remembered: it is re-derived until a non-passive request persists it.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task ValidateAsync_PassiveChangedRefresh_KeepsBeingRederived()
{
var clock = new TestTimeProvider(Start);
var mapper = new FakeGroupRoleMapper(new RoleMappingResult([Roles.Viewer], [], false));
var sut = CreateTrackedValidator(mapper, clock, new SessionActivityTracker());
var cookie = Session(Start, ["SCADA-Admins"], new RoleMappingResult([Roles.Administrator], [], true));
clock.Advance(TimeSpan.FromMinutes(16));
var first = await sut.ValidateAsync(cookie, recordActivity: false);
var second = await sut.ValidateAsync(cookie, recordActivity: false);
Assert.Equal(SessionValidationAction.Replace, first.Action);
Assert.Equal(SessionValidationAction.Replace, second.Action);
Assert.Equal([Roles.Viewer], second.Principal!.FindAll(JwtTokenService.RoleClaimType).Select(c => c.Value));
Assert.Equal(2, mapper.CallCount);
}
/// <summary>A refresh that keeps one role still replaces the principal (the zero-role rule is not over-broad).</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]