using Shouldly; using Xunit; using ZB.MOM.WW.OtOpcUa.Core.Abstractions; using ZB.MOM.WW.OtOpcUa.Core.Scripting; namespace ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests; /// /// lmxopcua#780 design §13 "Parity": the same script, through (today's guard) /// and through the worker, gives the same status, reason, value and exact CLR value type. /// [Collection(ScriptWorkerCollection.Name)] [Trait("Category", "ScriptWorker")] public sealed class ParityTests { private static CancellationToken Ct => TestContext.Current.CancellationToken; public static TheoryData Cases() => new() { { "arithmetic", "return 1 + 2;" }, { "string", "return \"a\" + ctx.GetTag(\"x\").Value;" }, { "throw", "throw new System.InvalidOperationException(\"boom\");" }, { "compile error", "return undefinedThing;" }, { "sandbox violation", "return System.IO.File.Exists(\"x\");" }, { "missing input status", "return ctx.GetTag(\"missing\").StatusCode;" }, { "input status", "return ctx.GetTag(\"x\").StatusCode;" }, { "source timestamp", "return ctx.GetTag(\"x\").SourceTimestampUtc;" }, { "clock", "return ctx.Now > new System.DateTime(2000, 1, 1);" }, { "null", "return null;" }, { "array", "return new double[] { 1.5, 2.5 };" }, { "cast of wrong type", "return (short)ctx.GetTag(\"x\").Value;" }, }; private static readonly IReadOnlyDictionary Inputs = new Dictionary(StringComparer.Ordinal) { ["x"] = new DataValueSnapshot(5, 0x40000000u, new DateTime(2026, 1, 2, 3, 4, 5, DateTimeKind.Utc), DateTime.UtcNow), }; [Theory] [MemberData(nameof(Cases))] public async Task In_and_out_of_process_agree(string name, string source) { using var inProcess = new InProcessScriptRunner(); await using var outOfProcess = Scripts.Runner(Scripts.Options()); var invocation = Scripts.Vt(name, source, inputs: Inputs); var expected = await inProcess.RunAsync(invocation, Ct); var actual = await outOfProcess.RunAsync(invocation, Ct); actual.Status.ShouldBe(expected.Status, $"{name}: {actual.Reason} vs {expected.Reason}"); actual.Reason.ShouldBe(expected.Reason); Same(actual.Value, expected.Value, name); } public static TheoryData Typed() => new() { { "bool", true }, { "sbyte", (sbyte)-2 }, { "byte", (byte)2 }, { "short", (short)-3 }, { "ushort", (ushort)3 }, { "int", -4 }, { "uint", 4u }, { "long", -5L }, { "ulong", 5UL }, { "float", 1.25f }, { "double", 2.5 }, { "string", "s" }, { "System.DateTime", new DateTime(2026, 11, 9, 0, 0, 0, DateTimeKind.Utc) }, // lmxopcua#1100: a Guid input used to fail "unsupported type" out of process. { "System.Guid", new Guid("0f8fad5b-d9cb-469f-a165-70867728950e") }, }; /// /// Unboxing parity (pins design assumption A-7): (T)ctx.GetTag("x").Value works out of process for every /// tag type, which needs the exact boxed CLR type to survive the wire. /// [Theory] [MemberData(nameof(Typed))] public async Task Unboxing_to_the_exact_type_matches(string typeName, object value) { using var inProcess = new InProcessScriptRunner(); await using var outOfProcess = Scripts.Runner(Scripts.Options()); var invocation = Scripts.Vt("unbox-" + typeName, $"var v = ({typeName})ctx.GetTag(\"x\").Value; return v;", inputs: Scripts.Input("x", value)); var expected = await inProcess.RunAsync(invocation, Ct); var actual = await outOfProcess.RunAsync(invocation, Ct); expected.Status.ShouldBe(ScriptRunStatus.Ok, expected.Reason); actual.Status.ShouldBe(ScriptRunStatus.Ok, actual.Reason); Same(actual.Value, expected.Value, typeName); } /// /// lmxopcua#1064: the result rule of #1059 () holds in both runners — a lazy /// sequence becomes the same typed array, and an over-cap / open-slot sequence fails with the same reason. Before /// the fix the worker answered every lazy sequence "unsupported type" and shipped an over-cap array whole. /// public static TheoryData ResultCases() => new() { { "lazy query", "return System.Linq.Enumerable.Range(0, 3).Select(i => i * 1.5);" }, { "iterator", "System.Collections.Generic.IEnumerable F() { for (var i = 0; i < 3; i++) yield return i; } return F();" }, { "endless iterator", "System.Collections.Generic.IEnumerable F() { var i = 0.0; while (true) yield return i++; } return F();" }, { "over-cap lazy", "return System.Linq.Enumerable.Range(0, int.MaxValue).Select(i => (double)i);" }, { "over-cap array", "return new double[5];" }, { "at-cap array", "return new double[4];" }, { "empty lazy", "return System.Linq.Enumerable.Empty();" }, // lmxopcua#1092: a concrete non-array collection. In process it used to come back as the List itself (capped by // Count, but not an array), while the worker answered "unsupported type" — now both return the same typed array. { "list", "return new System.Collections.Generic.List { 1.5, 2.5 };" }, { "at-cap list", "return new System.Collections.Generic.List { 1, 2, 3, 4 };" }, { "over-cap list", "return new System.Collections.Generic.List(new double[5]);" }, { "hash set", "return new System.Collections.Generic.HashSet { \"a\" };" }, { "queue", "var q = new System.Collections.Generic.Queue(); q.Enqueue(3); q.Enqueue(4); return q;" }, { "list of object", "return new System.Collections.Generic.List { 1, \"a\" };" }, { "nested list", "return new System.Collections.Generic.List> { new() { 1 } };" }, // lmxopcua#1100: both runners return what the OPC UA publish path can represent. A Guid (scalar, array, collection) // is an OPC UA built-in: in process it always reached the client, and the wire now carries it (it was "unsupported // type" out of process). A KeyValuePair[] — what a returned Dictionary becomes — a decimal, an enum, a TimeSpan or a // char has no OPC UA representation: in process the node write threw and the node silently kept its old value and // status, out of process it was "unsupported type"; now both refuse it with the same script-threw reason. { "guid", "return new System.Guid(\"0f8fad5b-d9cb-469f-a165-70867728950e\");" }, { "guid array", "return new[] { System.Guid.Empty, new System.Guid(\"0f8fad5b-d9cb-469f-a165-70867728950e\") };" }, { "guid list", "return new System.Collections.Generic.List { System.Guid.Empty };" }, { "dictionary", "return new System.Collections.Generic.Dictionary { [1] = 1.5 };" }, { "key-value pair array", "return new[] { new System.Collections.Generic.KeyValuePair(\"a\", 1) };" }, { "lazy key-value pairs", "return new System.Collections.Generic.Dictionary { [1] = 2 }.Where(p => p.Key > 0);" }, { "key-value pair", "return new System.Collections.Generic.KeyValuePair(1, 2);" }, { "decimal", "return 1.5m;" }, { "decimal array", "return new[] { 1.5m };" }, { "enum", "return System.DayOfWeek.Monday;" }, { "time span", "return System.TimeSpan.FromSeconds(1);" }, { "char array", "return new[] { 'a' };" }, { "two-dimensional array", "return new double[1, 1];" }, }; [Theory] [MemberData(nameof(ResultCases))] public async Task Result_materialisation_and_the_element_cap_agree(string name, string source) { const int cap = 4; using var inProcess = new InProcessScriptRunner(new ScriptingOptions { MaxResultElements = cap }); var options = Scripts.Options(); options.MaxResultElements = cap; await using var outOfProcess = Scripts.Runner(options); var invocation = Scripts.Vt("result-" + name, source); var expected = await inProcess.RunAsync(invocation, Ct); var actual = await outOfProcess.RunAsync(invocation, Ct); actual.Status.ShouldBe(expected.Status, $"{name}: {actual.Reason} vs {expected.Reason}"); actual.Reason.ShouldBe(expected.Reason); Same(actual.Value, expected.Value, name); } /// /// lmxopcua#1092 positive control for the theory above (it would also pass if both runners refused a List): a /// returned List<double> is the same double[] in both runners. /// [Fact] public async Task A_returned_list_is_the_same_typed_array_in_both_runners() { using var inProcess = new InProcessScriptRunner(new ScriptingOptions { MaxResultElements = 4 }); var options = Scripts.Options(); options.MaxResultElements = 4; await using var outOfProcess = Scripts.Runner(options); var invocation = Scripts.Vt("result-list-control", "return new System.Collections.Generic.List { 1.5, 2.5 };"); foreach (var outcome in new[] { await inProcess.RunAsync(invocation, Ct), await outOfProcess.RunAsync(invocation, Ct) }) { outcome.Status.ShouldBe(ScriptRunStatus.Ok, outcome.Reason); outcome.Value.ShouldBeOfType().ShouldBe([1.5, 2.5]); } } /// /// lmxopcua#1100 controls for the rows above, which would also pass if both runners refused everything or returned /// everything: a Guid array is the same Guid[] in both runners, and a dictionary is refused in both with the /// reason that says what to return instead. /// [Fact] public async Task A_guid_array_crosses_and_a_dictionary_is_refused_in_both_runners() { using var inProcess = new InProcessScriptRunner(); await using var outOfProcess = Scripts.Runner(Scripts.Options()); var guid = new Guid("0f8fad5b-d9cb-469f-a165-70867728950e"); var guids = Scripts.Vt("result-guid-control", $"return new[] {{ System.Guid.Empty, new System.Guid(\"{guid}\") }};"); var dictionary = Scripts.Vt("result-dictionary-control", "return new System.Collections.Generic.Dictionary { [1] = 1.5 };"); foreach (var outcome in new[] { await inProcess.RunAsync(guids, Ct), await outOfProcess.RunAsync(guids, Ct) }) { outcome.Status.ShouldBe(ScriptRunStatus.Ok, outcome.Reason); outcome.Value.ShouldBeOfType().ShouldBe([Guid.Empty, guid]); } foreach (var outcome in new[] { await inProcess.RunAsync(dictionary, Ct), await outOfProcess.RunAsync(dictionary, Ct) }) { outcome.Status.ShouldBe(ScriptRunStatus.Failed); outcome.Reason.ShouldBe( "script threw: The script returned a value of type 'KeyValuePair[]', which an OPC UA node cannot carry; " + "return null, a bool, an integer type, float, double, string, DateTime or Guid, or a one-dimensional array of one of " + "them (convert first, e.g. Convert.ToDouble(x) for a decimal, or the keys and values of a dictionary as two arrays)."); } } [Fact] public async Task The_worker_holds_a_lazy_result_to_the_configured_cap() { // Positive control first (the cap is not simply "always fails"): 3 elements under a cap of 3 materialise. var options = Scripts.Options(); options.MaxResultElements = 3; await using var runner = Scripts.Runner(options); var ok = await runner.RunAsync(Scripts.Vt("cap-ok", "return System.Linq.Enumerable.Range(0, 3).Select(i => (double)i);"), Ct); ok.Status.ShouldBe(ScriptRunStatus.Ok, ok.Reason); ok.Value.ShouldBeOfType().ShouldBe([0.0, 1.0, 2.0]); var over = await runner.RunAsync(Scripts.Vt("cap-over", "return System.Linq.Enumerable.Range(0, 4).Select(i => (double)i);"), Ct); over.Status.ShouldBe(ScriptRunStatus.Failed); over.Reason.ShouldNotBeNull().ShouldContain("more than 3 elements"); } private static void Same(object? actual, object? expected, string because) { if (expected is null) { actual.ShouldBeNull(because); return; } actual.ShouldNotBeNull(because); actual.GetType().ShouldBe(expected.GetType(), because); if (expected is Array array) ((Array)actual).Cast().ShouldBe(array.Cast(), because); else actual.ShouldBe(expected, because); } }