Merge scripting follow-ups: one shared compile rule for editor + gate, CS0161/injection now flagged in the editor (#1063), worker applies the result materialisation cap (#1064), {{equip}} in Calculation scripts refused at gate + editor (#1065)
This commit is contained in:
@@ -105,8 +105,43 @@ public sealed class DiagnoseTests
|
||||
=> Diag("""var p = "A"; return ctx.GetTag(p).Value;""")
|
||||
.ShouldContain(x => x.Message.Contains("literal"));
|
||||
|
||||
[Fact] public void Missing_return_does_not_produce_a_phantom_preamble_marker()
|
||||
=> Diag("var x = 1;").ShouldNotContain(m => m.Code == "CS0161");
|
||||
// lmxopcua#1063: this used to assert the OPPOSITE ("does not produce a phantom preamble marker"). CS0161 is not a
|
||||
// phantom: Roslyn pins it on the wrapper's Run, and the runtime compile / deploy gate refuse the script. It is now
|
||||
// reported, on the script's last line (the wrapper location means "the script as a whole").
|
||||
[Fact] public void Missing_return_is_an_error_on_the_scripts_last_line()
|
||||
{
|
||||
var m = Diag("var x = 1;\nvar y = x + 1;").Single(x => x.Code == "CS0161");
|
||||
m.Severity.ShouldBe(8);
|
||||
m.StartLineNumber.ShouldBe(2);
|
||||
m.EndLineNumber.ShouldBe(2);
|
||||
m.StartColumn.ShouldBe(1);
|
||||
m.EndColumn.ShouldBe("var y = x + 1;".Length + 1);
|
||||
m.Message.ShouldBe(ScriptAnalysisService.NotAllPathsReturnMessage);
|
||||
}
|
||||
|
||||
[Fact] public void Trailing_blank_lines_do_not_move_the_whole_script_marker_onto_nothing()
|
||||
{
|
||||
var m = Diag("var x = 1;\nvar y = x + 1;\n\n \n").Single(x => x.Code == "CS0161");
|
||||
m.StartLineNumber.ShouldBe(2);
|
||||
m.EndColumn.ShouldBe("var y = x + 1;".Length + 1);
|
||||
}
|
||||
|
||||
[Fact] public void A_blank_predicate_is_refused_like_the_gate_refuses_it()
|
||||
{
|
||||
// A blank VALUE script never compiles at runtime (passes); a blank PREDICATE compiles and fails CS0161.
|
||||
Diag("").ShouldBeEmpty();
|
||||
Svc.Diagnose(new DiagnoseRequest("", Mode: ScriptAnalysisModes.AlarmPredicate), TestContext.Current.CancellationToken)
|
||||
.Markers.ShouldContain(m => m.Code == "CS0161" && m.StartLineNumber == 1 && m.EndColumn >= 1);
|
||||
}
|
||||
|
||||
[Fact] public void A_path_that_falls_off_the_end_is_an_error()
|
||||
=> Diag("""if (ctx.GetTag("A").Value is null) return 1;""").ShouldContain(m => m.Code == "CS0161" && m.Severity == 8);
|
||||
|
||||
[Fact] public void Every_path_returning_is_clean_positive_control()
|
||||
=> Diag("""if (ctx.GetTag("A").Value is null) return 1; return 2;""").ShouldBeEmpty();
|
||||
|
||||
[Fact] public void A_wrapper_injection_is_an_error_like_the_runtime_compile()
|
||||
=> Diag("return 0; } public static int Evil() { return 0;").ShouldContain(m => m.Code == "LMX002" && m.Severity == 8);
|
||||
|
||||
[Fact] public void Empty_code_has_no_markers()
|
||||
=> Diag("").ShouldBeEmpty();
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.AdminUI.ScriptAnalysis;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Scripting;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.ScriptAnalysis;
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#1063 / #1065 — "the editor accepts ⇔ publish accepts", checked over one corpus in all three editor modes
|
||||
/// against the deploy gate's own checker (<see cref="RoslynDeployScriptChecker"/>, the seam the mode names). The
|
||||
/// editor used to drop wrapper-located errors, so a script with a path that does not return (CS0161) was clean in the
|
||||
/// editor and refused at deploy; and a Calculation script carrying <c>{{equip}}</c> was accepted by both and read Bad
|
||||
/// forever. Both sides now share <see cref="ScriptCompileRules"/> and <see cref="EquipTokenLiteralScanner"/>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Excluded on purpose: a DYNAMIC tag path (<c>ctx.GetTag(variable)</c>) in a value or Calculation script. The editor
|
||||
/// marks it an error in every mode while the gate refuses it only for a scripted-alarm predicate — a known,
|
||||
/// editor-stricter divergence tracked separately (it is not a compile rule, and either fix changes behaviour).
|
||||
/// </remarks>
|
||||
public sealed class EditorGateParityTests
|
||||
{
|
||||
private static readonly ScriptAnalysisService Svc = new();
|
||||
private static readonly RoslynDeployScriptChecker Gate = new();
|
||||
|
||||
public static TheoryData<string, string> Corpus()
|
||||
{
|
||||
string[] sources =
|
||||
[
|
||||
// CS0161 family (#1063): a path that falls off the end, no return at all, blank, whitespace-only.
|
||||
"var x = 1;",
|
||||
"""if (ctx.GetTag("A").Value is null) return 1;""",
|
||||
"""if (ctx.GetTag("A").Value is null) return true;""",
|
||||
"",
|
||||
" \n ",
|
||||
"while (true) { }",
|
||||
"throw new System.InvalidOperationException(\"x\");",
|
||||
// Well-formed returns: value and bool.
|
||||
"""if (ctx.GetTag("A").Value is null) return 1; return 2;""",
|
||||
"""return ctx.GetTag("A").Value;""",
|
||||
"""return Convert.ToDouble(ctx.GetTag("A").Value ?? 0.0) > 5;""",
|
||||
"return true;",
|
||||
"return null;",
|
||||
"return;",
|
||||
// Ordinary compile errors, sandbox, injection (LMX001/002).
|
||||
"var x = ; return 1;",
|
||||
"return ctx.Nope();",
|
||||
"""var f = new System.IO.FileInfo("/x"); return 1;""",
|
||||
"return 0; } public static int Evil() { return 0;",
|
||||
"return 0; } } class Evil { ",
|
||||
"return 1; }",
|
||||
"{ return 1;",
|
||||
// {{equip}} (#1056 / #1065): substituted regular literal, passthrough shape, verbatim, interpolated, mid-path.
|
||||
"""return ctx.GetTag("{{equip}}/Speed").Value;""",
|
||||
"""return (double)ctx.GetTag("{{equip}}/Speed").Value * 2;""",
|
||||
"""return ctx.GetTag(@"{{equip}}/Speed").Value;""",
|
||||
"""return ctx.GetTag($"{{equip}}/Speed").Value;""",
|
||||
"""return ctx.GetTag("Plant/{{equip}}/Speed").Value;""",
|
||||
"""ctx.SetVirtualTag("{{equip}}/Out", 1); return 1;""",
|
||||
"""ctx.Logger.Information("{{equip}} is only a log string"); return 1;""",
|
||||
];
|
||||
string[] modes = [ScriptAnalysisModes.Value, ScriptAnalysisModes.Calculation, ScriptAnalysisModes.AlarmPredicate];
|
||||
var data = new TheoryData<string, string>();
|
||||
foreach (var mode in modes)
|
||||
foreach (var source in sources)
|
||||
data.Add(mode, source);
|
||||
return data;
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(Corpus))]
|
||||
public void Editor_and_gate_agree(string mode, string source)
|
||||
{
|
||||
var markers = Svc.Diagnose(new DiagnoseRequest(source, Mode: mode), TestContext.Current.CancellationToken).Markers;
|
||||
var editorRejects = markers.Any(m => m.Severity == 8);
|
||||
var verdict = Gate.Check(
|
||||
[new DeployScriptCheckRequest(ScriptAnalysisModes.KindOf(mode), source)], TestContext.Current.CancellationToken)[0];
|
||||
editorRejects.ShouldBe(!verdict.Passed,
|
||||
$"mode {mode}, source <{source}>: editor [{string.Join(" | ", markers.Select(m => m.Code + " " + m.Message))}] " +
|
||||
$"vs gate [{string.Join(" | ", verdict.Problems)}]");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_missing_return_is_refused_by_both_positive_control_for_the_parity_theory()
|
||||
{
|
||||
// Pins that the corpus really exercises #1063 — both sides REFUSE it (a parity theory where both accepted
|
||||
// everything would pass vacuously).
|
||||
const string source = """if (ctx.GetTag("A").Value is null) return 1;""";
|
||||
Svc.Diagnose(new DiagnoseRequest(source), TestContext.Current.CancellationToken).Markers.ShouldContain(m => m.Code == "CS0161" && m.Severity == 8);
|
||||
Gate.Check([new DeployScriptCheckRequest(ScriptContextKind.VirtualTag, source)], TestContext.Current.CancellationToken)[0]
|
||||
.Problems.ShouldContain(p => p.Contains("CS0161"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equip_in_a_calculation_is_refused_by_both_but_accepted_by_both_for_a_virtual_tag()
|
||||
{
|
||||
const string source = """return ctx.GetTag("{{equip}}/Speed").Value;""";
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
Svc.Diagnose(new DiagnoseRequest(source, Mode: ScriptAnalysisModes.Calculation), TestContext.Current.CancellationToken).Markers
|
||||
.ShouldContain(m => m.Code == "OTSCRIPT_EQUIPCALC" && m.Severity == 8);
|
||||
Gate.Check([new DeployScriptCheckRequest(ScriptContextKind.Calculation, source)], ct)[0].Passed.ShouldBeFalse();
|
||||
// Positive control: the same text is the normal VirtualTag template form.
|
||||
Svc.Diagnose(new DiagnoseRequest(source, Mode: ScriptAnalysisModes.Value), TestContext.Current.CancellationToken).Markers.ShouldBeEmpty();
|
||||
Gate.Check([new DeployScriptCheckRequest(ScriptContextKind.VirtualTag, source)], ct)[0].Passed.ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_editor_wraps_scripts_in_the_runtimes_own_wrapper_text()
|
||||
{
|
||||
var tree = Svc.CompilationFor("return 1;").SyntaxTrees.Single().ToString();
|
||||
tree.ShouldBe(ScriptEvaluator<ZB.MOM.WW.OtOpcUa.Core.VirtualTags.VirtualTagContext, object?>.WrapperPreamble
|
||||
+ "return 1;" + ScriptEvaluator<ZB.MOM.WW.OtOpcUa.Core.VirtualTags.VirtualTagContext, object?>.WrapperSuffix);
|
||||
var predicate = Svc.CompilationFor("return true;", ScriptAnalysisModes.AlarmPredicate).SyntaxTrees.Single().ToString();
|
||||
predicate.ShouldBe(ScriptEvaluator<ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.AlarmPredicateContext, bool>.WrapperPreamble
|
||||
+ "return true;" + ScriptEvaluator<ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.AlarmPredicateContext, bool>.WrapperSuffix);
|
||||
}
|
||||
}
|
||||
+29
@@ -63,5 +63,34 @@ public sealed class ScriptUsageClassifyTests
|
||||
}));
|
||||
u.UsedAsValue.ShouldBeTrue();
|
||||
u.UsedAsPredicate.ShouldBeFalse();
|
||||
// #1065: a Calculation use opens the editor in Calculation mode ({{equip}} refused, as the deploy gate does).
|
||||
u.UsedAsCalculation.ShouldBeTrue();
|
||||
u.DefaultMode.ShouldBe(ScriptAnalysisModes.Calculation);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_script_shared_by_a_virtual_tag_and_a_calculation_tag_opens_in_calculation_mode()
|
||||
{
|
||||
// Calculation mode is the value shape plus the one Calculation-only refusal, so it shows every refusal either
|
||||
// value use can meet; value mode would hide the {{equip}} refusal of the Calculation use.
|
||||
var u = await Classify(db =>
|
||||
{
|
||||
db.VirtualTags.Add(new VirtualTag { VirtualTagId = "vt-1", EquipmentId = "eq", Name = "v", DataType = "Double", ScriptId = "s-1" });
|
||||
db.Tags.Add(new Tag
|
||||
{
|
||||
TagId = "t-1", DeviceId = "d", Name = "calc", DataType = "Double", AccessLevel = ZB.MOM.WW.OtOpcUa.Configuration.Enums.TagAccessLevel.Read, TagConfig = "{\"scriptId\":\"s-1\"}",
|
||||
});
|
||||
});
|
||||
u.UsedAsCalculation.ShouldBeTrue();
|
||||
u.DefaultMode.ShouldBe(ScriptAnalysisModes.Calculation);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_virtual_tag_only_script_is_not_a_calculation_script()
|
||||
{
|
||||
var u = await Classify(db =>
|
||||
db.VirtualTags.Add(new VirtualTag { VirtualTagId = "vt-1", EquipmentId = "eq", Name = "v", DataType = "Double", ScriptId = "s-1" }));
|
||||
u.UsedAsCalculation.ShouldBeFalse();
|
||||
u.DefaultMode.ShouldBe(ScriptAnalysisModes.Value);
|
||||
}
|
||||
}
|
||||
|
||||
+20
@@ -211,6 +211,26 @@ public sealed class AdminOperationsActorScriptCompileGateTests : ControlPlaneAct
|
||||
reply.Message.ShouldContain("Calculation tag 'tag-calc' (plant/calc/cdev/sum)");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#1065: a Calculation tag has no equipment, and the Calculation seam never substitutes <c>{{equip}}</c>,
|
||||
/// so a Calculation script carrying it used to deploy clean and read <c>{{equip}}/speed</c> literally — Bad forever.
|
||||
/// The gate now refuses it (the passthrough shape too, which never reaches Roslyn), naming the Calculation tag;
|
||||
/// the VirtualTag in the same draft uses the token legitimately (positive control: it is not named).
|
||||
/// </summary>
|
||||
[Theory]
|
||||
[InlineData("return ctx.GetTag(\"{{equip}}/speed\").Value;")]
|
||||
[InlineData("return Convert.ToDouble(ctx.GetTag(\"{{equip}}/speed\").Value ?? 0.0) + 1;")]
|
||||
public void An_equip_token_in_a_calculation_script_is_refused_naming_the_calculation_tag(string calcSource)
|
||||
{
|
||||
var reply = Deploy(SeedDraft(new Seed(CalcSource: calcSource)), new RoslynDeployScriptChecker(), expectDispatch: false);
|
||||
reply.Outcome.ShouldBe(StartDeploymentOutcome.Rejected);
|
||||
reply.Message.ShouldNotBeNull();
|
||||
reply.Message.ShouldContain("script 's-calc' does not compile as a Calculation script");
|
||||
reply.Message.ShouldContain("Calculation tag 'tag-calc' (plant/calc/cdev/sum)");
|
||||
reply.Message.ShouldContain("equip token in a Calculation script");
|
||||
reply.Message.ShouldNotContain("script 's-vt'");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Disabled_users_are_not_checked_they_never_compile_at_runtime()
|
||||
{
|
||||
|
||||
@@ -80,6 +80,58 @@ public sealed class ParityTests
|
||||
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>();" },
|
||||
};
|
||||
|
||||
[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);
|
||||
}
|
||||
|
||||
[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)
|
||||
|
||||
Reference in New Issue
Block a user