d81990bcbf
int[][] / byte[][] used to be the one result divergence left after #1100: in process ScriptResultMaterializer passed it (SdkValueBoundary.FromClr carries it as an array of Variants), while the worker's wire has no nested-array tag and answered "unsupported type". A script-fed node has a scalar DataType, so a Variant-of-arrays value is not what it declares either; not documented as a feature anywhere (only noted as the known divergence). Decision: refuse, via the shared rule. - IsPublishable: a 1-D array's element must be a PublishableScalarTypes scalar (no recursion). - EnsurePublishable: a nested array gets its own reason, still "... which an OPC UA node cannot carry: an array of arrays ...", with a flatten hint (SelectMany). Same "script threw: ..." text in both runners. - SdkValueBoundaryScriptResultTests: int[][] leaves the rule==FromClr theory; a separate fact pins the one deliberate difference (FromClr takes it, the rule refuses). - ParityTests: "jagged array" + "jagged byte array" rows. ShadowModeTests census: the jagged script now MATCHES; the unsupported_type mismatch is exercised by a decimal INPUT (design §14 #11), the real remaining worker-only refusal. - ContainmentTests.Unsupported_input_and_result_types: jagged now expects the materializer reason. Mutation: restoring the recursive element check fails 4 tests (2 parity rows, shadow census, containment unsupported-type). Behaviour change: a value script returning a jagged array now fails (Bad + script log) in process too, instead of publishing a Variant array onto a scalar-typed node.
230 lines
13 KiB
C#
230 lines
13 KiB
C#
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;
|
|
|
|
/// <summary>
|
|
/// lmxopcua#780 design §13 "Parity": the same script, through <see cref="InProcessScriptRunner"/> (today's guard)
|
|
/// and through the worker, gives the same status, reason, value and exact CLR value type.
|
|
/// </summary>
|
|
[Collection(ScriptWorkerCollection.Name)]
|
|
[Trait("Category", "ScriptWorker")]
|
|
public sealed class ParityTests
|
|
{
|
|
private static CancellationToken Ct => TestContext.Current.CancellationToken;
|
|
|
|
public static TheoryData<string, string> 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<string, DataValueSnapshot> Inputs =
|
|
new Dictionary<string, DataValueSnapshot>(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<string, object> 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") },
|
|
};
|
|
|
|
/// <summary>
|
|
/// Unboxing parity (pins design assumption A-7): <c>(T)ctx.GetTag("x").Value</c> works out of process for every
|
|
/// tag type, which needs the exact boxed CLR type to survive the wire.
|
|
/// </summary>
|
|
[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);
|
|
}
|
|
|
|
/// <summary>
|
|
/// lmxopcua#1064: the result rule of #1059 (<see cref="ScriptResultMaterializer"/>) 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.
|
|
/// </summary>
|
|
public static TheoryData<string, string> ResultCases() => new()
|
|
{
|
|
{ "lazy query", "return System.Linq.Enumerable.Range(0, 3).Select(i => i * 1.5);" },
|
|
{ "iterator", "System.Collections.Generic.IEnumerable<int> F() { for (var i = 0; i < 3; i++) yield return i; } return F();" },
|
|
{ "endless iterator", "System.Collections.Generic.IEnumerable<double> 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<string>();" },
|
|
// 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<double> { 1.5, 2.5 };" },
|
|
{ "at-cap list", "return new System.Collections.Generic.List<int> { 1, 2, 3, 4 };" },
|
|
{ "over-cap list", "return new System.Collections.Generic.List<double>(new double[5]);" },
|
|
{ "hash set", "return new System.Collections.Generic.HashSet<string> { \"a\" };" },
|
|
{ "queue", "var q = new System.Collections.Generic.Queue<long>(); q.Enqueue(3); q.Enqueue(4); return q;" },
|
|
{ "list of object", "return new System.Collections.Generic.List<object> { 1, \"a\" };" },
|
|
{ "nested list", "return new System.Collections.Generic.List<System.Collections.Generic.List<int>> { 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> { System.Guid.Empty };" },
|
|
{ "dictionary", "return new System.Collections.Generic.Dictionary<int, double> { [1] = 1.5 };" },
|
|
{ "key-value pair array", "return new[] { new System.Collections.Generic.KeyValuePair<string, int>(\"a\", 1) };" },
|
|
{ "lazy key-value pairs", "return new System.Collections.Generic.Dictionary<int, int> { [1] = 2 }.Where(p => p.Key > 0);" },
|
|
{ "key-value pair", "return new System.Collections.Generic.KeyValuePair<int, int>(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];" },
|
|
// lmxopcua#1104: an array of arrays — in process it used to publish (as an array of Variants) while the worker
|
|
// answered "unsupported type"; both now refuse it with the same flatten hint.
|
|
{ "jagged array", "return new[] { new[] { 1, 2 }, new[] { 3 } };" },
|
|
{ "jagged byte array", "return new[] { new byte[] { 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);
|
|
}
|
|
|
|
/// <summary>
|
|
/// lmxopcua#1092 positive control for the theory above (it would also pass if both runners refused a List): a
|
|
/// returned <c>List<double></c> is the same <c>double[]</c> in both runners.
|
|
/// </summary>
|
|
[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<double> { 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<double[]>().ShouldBe([1.5, 2.5]);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 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 <c>Guid[]</c> in both runners, and a dictionary is refused in both with the
|
|
/// reason that says what to return instead.
|
|
/// </summary>
|
|
[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<int, double> { [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<Guid[]>().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<Int32, Double>[]', 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<double[]>().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<object?>().ShouldBe(array.Cast<object?>(), because);
|
|
else actual.ShouldBe(expected, because);
|
|
}
|
|
}
|